normalizr API

API

  • normalize
  • denormalize
  • schema
    • Array
    • Entity
    • Object
    • Union
    • Values

normalize(data, schema)

Normalizes input data per the schema definition provided.?

根據提供的schema定義規范化輸入數據。

  • data: required Input JSON (or plain JS object) data that needs normalization.
  • schema: required A schema definition

Usage

import { normalize, schema } from 'normalizr';const myData = { users: [ { id: 1 }, { id: 2 } ] };
const user = new schema.Entity('users');
const mySchema = { users: [ user ] }
const normalizedData = normalize(myData, mySchema);復制代碼

Output

{result: { users: [ 1, 2 ] },entities: {users: {'1': { id: 1 },'2': { id: 2 }}}
}復制代碼

denormalize(input, schema, entities)

Denormalizes an input based on schema and provided entities from a plain object or Immutable data. The reverse of normalize.

基于schema和從普通對象或不可變數據提供的實體對輸入數據進行去規范化。 與規范化相反。

Special Note:
Be careful with denormalization. Prematurely reverting your data to large, nested objects could cause performance impacts in React (and other) applications.

小心非規范化。 過早將數據還原到大型嵌套對象可能會對React(和其他)應用程序造成性能影響。

If your schema and data have recursive references, only the first instance of an entity will be given. Subsequent references will be returned as the id provided.

如果您的schema和數據具有遞歸引用,則只會給出實體的第一個實例。 隨后的引用將返回給ID。

  • input: required The normalized result that should be
    de-normalized
    . Usually the same value that was given in the result key of the output of normalize. 通常在規范化輸出的結果鍵中給出相同的值。
  • schema: required A schema definition that was used to get the value for input.
  • entities: required An object, keyed by entity schema names that may appear in the denormalized output. Also accepts an object with Immutable data.

Usage

import { denormalize, schema } from 'normalizr';const user = new schema.Entity('users');
const mySchema = { users: [ user ] }
const entities = { users: { '1': { id: 1 }, '2': { id: 2 } } };
const denormalizedData = denormalize({ users: [ 1, 2 ] }, mySchema, entities);復制代碼

Output

{ users: [{ id: 1 },{ id: 2 }]
}復制代碼

schema

Array(definition, schemaAttribute)

Creates a schema to normalize an array of entities. If the input value is an Object instead of an Array, the normalized result will be an Array of the Object's values.

創建一個schema來規范化實體數組。 如果輸入值是Object而不是Array,則歸一化結果將是Object的值的Array。

Note: The same behavior can be defined with shorthand syntax: [ mySchema ]

相同的行為可以用速記語法來定義

  • definition: required A singular schema that this array contains
    or a mapping of schema to attribute values.
需要此數組包含的單一schema?或將schema?映射到屬性值。
  • schemaAttribute:
    optional
    (required if definition is not a singular schema) The attribute on each entity found that defines what schema, per the definition mapping, to use when normalizing.
    Can be a string or a function. If given a function, accepts the following arguments:
    • value: The input value of the entity.
    • parent: The parent object of the input array.
    • key: The key at which the input array appears on the parent object.

Instance Methods

  • define(definition): When used, the definition passed in will be merged with the original definition passed to the Array constructor. This method tends to be useful for creating circular references in schema.
使用時,傳入的definition將與傳遞給Array構造函數的原始definition合并。 該方法往往對于在schema中創建循環引用很有用。

Usage

To describe a simple array of a singular entity type:

const data = [ { id: '123', name: 'Jim' }, { id: '456', name: 'Jane' } ];
const userSchema = new schema.Entity('users');const userListSchema = new schema.Array(userSchema);
// or use shorthand syntax:
const userListSchema = [ userSchema ];const normalizedData = normalize(data, userListSchema);復制代碼

Output

{entities: {users: {'123': { id: '123', name: 'Jim' },'456': { id: '456', name: 'Jane' }}},result: [ '123', '456' ]
}復制代碼

If your input data is an array of more than one type of entity, it is necessary to define a schema mapping.

如果您的輸入數據是多個類型的實體的數組,則需要定義一個schema映射。

Note: If your data returns an object that you did not provide a mapping for, the original object will be returned in the result and an entity will not be created.

如果您的數據返回一個未提供映射的對象,則將返回原始對象,并且不會創建一個實體。

For example:

const data = [ { id: 1, type: 'admin' }, { id: 2, type: 'user' } ];const userSchema = new schema.Entity('users');
const adminSchema = new schema.Entity('admins');
const myArray = new schema.Array({admins: adminSchema,users: userSchema
}, (input, parent, key) => `${input.type}s`);const normalizedData = normalize(data, myArray);復制代碼

Output

{entities: {admins: { '1': { id: 1, type: 'admin' } },users: { '2': { id: 2, type: 'user' } }},result: [{ id: 1, schema: 'admins' },{ id: 2, schema: 'users' }]
}復制代碼

Entity(key, definition = {}, options = {})

  • key: required The key name under which all entities of this type will be listed in the normalized response. Must be a string name.
  • definition: A definition of the nested entities found within this entity. Defaults to empty object.
在該實體內發現的嵌套實體的definition。 默認為空對象。
You do not need to define any keys in your entity other than those that hold nested entities. All other values will be copied to the normalized entity's output.
您不需要在您的實體中定義任何鍵,除了嵌套實體的鍵。 所有其他值將被復制到標準化實體的輸出。definition不為空表示有嵌套。
  • options:
    • idAttribute: The attribute where unique IDs for each of this entity type can be found.
      Accepts either a string key or a function that returns the IDs value. Defaults to 'id'.
      As a function, accepts the following arguments, in order:
      • value: The input value of the entity.
      • parent: The parent object of the input array.
      • key: The key at which the input array appears on the parent object. 輸入的數組出現在父對象上的鍵。
    • mergeStrategy(entityA, entityB): Strategy to use when merging two entities with the same id value. Defaults to merge the more recently found entity onto the previous.
合并具有相同ID值的兩個實體時使用的策略。 默認將最近發現的實體合并到上一個實體。
    • processStrategy(value, parent, key): Strategy to use when pre-processing the entity. Use this method to add extra data, defaults, and/or completely change the entity before normalization is complete. Defaults to returning a shallow copy of the input entity.
預處理實體時使用的策略。 在規范化完成之前,使用此方法添加額外的數據,默認值和/或完全更改實體。 默認返回輸入實體的淺拷貝。
Note: It is recommended to always return a copy of your input and not modify the original.
建議始終返回您的輸入的副本,而不是修改原件。
The function accepts the following arguments, in order:
  • value: The input value of the entity.
  • parent: The parent object of the input array.
  • key: The key at which the input array appears on the parent object.

Instance Methods

  • define(definition): When used, the definition passed in will be merged with the original definition passed to the Entity constructor. This method tends to be useful for creating circular references in schema.
使用時,傳入的definition將與傳遞給Entity構造函數的原始definition合并。 該方法往往對于在模式中創建循環引用很有用。

Instance Attributes

  • key: Returns the key provided to the constructor.
  • idAttribute: Returns the idAttribute provided to the constructor in options.

Usage

const data = { id_str: '123', url: 'https://twitter.com', user: { id_str: '456', name: 'Jimmy' } };const user = new schema.Entity('users', {}, { idAttribute: 'id_str' });
const tweet = new schema.Entity('tweets', { user: user }, { idAttribute: 'id_str',// Apply everything from entityB over entityA, except for "favorites"mergeStrategy: (entityA, entityB) => ({...entityA,...entityB,favorites: entityA.favorites}),// Remove the URL field from the entityprocessStrategy: (entity) => omit(entity, 'url')
});const normalizedData = normalize(data, tweet);復制代碼

Output

{entities: {tweets: { '123': { id_str: '123', user: '456' } },users: { '456': { id_str: '456', name: 'Jimmy' } }},result: '123'
}復制代碼

idAttribute Usage

When passing the idAttribute a function, it should return the IDs value.

idAttribute作為key

For Example:

const data = [{ id: '1', guest_id: null, name: 'Esther' },{ id: '1', guest_id: '22', name: 'Tom' },
];const patronsSchema = new schema.Entity('patrons', undefined, {// idAttribute *functions* must return the ids **value** (not key)idAttribute: value => value.guest_id ? `${value.id}-${value.guest_id}` : value.id,
});normalize(data, [patronsSchema]);復制代碼

Output

{entities: {patrons: {'1': { id: '1', guest_id: null, name: 'Esther' },'1-22': { id: '1', guest_id: '22', name: 'Tom' },}},result: ['1', '1-22']
}復制代碼

Object(definition)

Define a plain object mapping that has values needing to be normalized into Entities.

定義一個普通對象映射,它需要將值歸一化為Entities。

Note: The same behavior can be defined with shorthand syntax: { ... }

  • definition: required A definition of the nested entities found within this object. Defaults to empty object.
    You do not need to define any keys in your object other than those that hold other entities. All other values will be copied to the normalized output.

Instance Methods

  • define(definition): When used, the definition passed in will be merged with the original definition passed to the Object constructor. This method tends to be useful for creating circular references in schema.

Usage

// Example data response
const data = { users: [ { id: '123', name: 'Beth' } ] };const user = new schema.Entity('users');
const responseSchema = new schema.Object({ users: new schema.Array(user) });
// or shorthand
const responseSchema = { users: new schema.Array(user) };const normalizedData = normalize(data, responseSchema);復制代碼

Output

{entities: {users: { '123': { id: '123', name: 'Beth' } }},result: { users: [ '123' ] }
}復制代碼

Union(definition, schemaAttribute)

Describe a schema which is a union of multiple schemas. This is useful if you need the polymorphic behavior provided by schema.Array or schema.Values but for non-collection fields.

描述一個多個schema的并集的schema。 如果您需要由schema.Arrayschema.Values提供的多態性行為,但對于非收集字段,這是非常有用的。

  • definition: required An object mapping the definition of the nested entities found within the input array
  • schemaAttribute: required The attribute on each entity found that defines what schema, per the definition mapping, to use when normalizing.
    Can be a string or a function. If given a function, accepts the following arguments:
    • value: The input value of the entity.
    • parent: The parent object of the input array.
    • key: The key at which the input array appears on the parent object.

Instance Methods

  • define(definition): When used, the definition passed in will be merged with the original definition passed to the Union constructor. This method tends to be useful for creating circular references in schema.

Usage

Note: If your data returns an object that you did not provide a mapping for, the original object will be returned in the result and an entity will not be created.

const data = { owner: { id: 1, type: 'user', name: 'Anne' } };const user = new schema.Entity('users');
const group = new schema.Entity('groups');
const unionSchema = new schema.Union({user: user,group: group
}, 'type');const normalizedData = normalize(data, { owner: unionSchema });復制代碼

Output

{entities: {users: { '1': { id: 1, type: 'user', name: 'Anne' } }},result: { owner: { id: 1, schema: 'user' } }
}復制代碼

Values(definition, schemaAttribute)

Describes a map whose values follow the given schema.

  • definition: required A singular schema that this array contains
    or a mapping of schema to attribute values.
  • schemaAttribute:
    optional
    (required if definition is not a singular schema) The attribute on each entity found that defines what schema, per the definition mapping, to use when normalizing.
    Can be a string or a function. If given a function, accepts the following arguments:
    • value: The input value of the entity.
    • parent: The parent object of the input array.
    • key: The key at which the input array appears on the parent object.

Instance Methods

  • define(definition): When used, the definition passed in will be merged with the original definition passed to the Values constructor. This method tends to be useful for creating circular references in schema.

Usage

const data = { firstThing: { id: 1 }, secondThing: { id: 2 } };const item = new schema.Entity('items');
const valuesSchema = new schema.Values(item);const normalizedData = normalize(data, valuesSchema);復制代碼

Output

{entities: {items: { '1': { id: 1 }, '2': { id: 2 } }},result: { firstThing: 1, secondThing: 2 }
}復制代碼

If your input data is an object that has values of more than one type of entity, but their schema is not easily defined by the key, you can use a mapping of schema, much like schema.Union and schema.Array.

Note: If your data returns an object that you did not provide a mapping for, the original object will be returned in the result and an entity will not be created.

For example:

const data = {'1': { id: 1, type: 'admin' }, '2': { id: 2, type: 'user' }
};const userSchema = new schema.Entity('users');
const adminSchema = new schema.Entity('admins');
const valuesSchema = new schema.Values({admins: adminSchema,users: userSchema
}, (input, parent, key) => `${input.type}s`);const normalizedData = normalize(data, valuesSchema);復制代碼

Output

{entities: {admins: { '1': { id: 1, type: 'admin' } },users: { '2': { id: 2, type: 'user' } }},result: {'1': { id: 1, schema: 'admins' },'2': { id: 2, schema: 'users' }}
}復制代碼



本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/540440.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/540440.shtml
英文地址,請注明出處:http://en.pswp.cn/news/540440.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

[轉載] 【Java】基礎06:HelloWorld入門程序

參考鏈接: 從Hello World示例開始Java編程 HelloWorld它的中文意思是:“你好,世界”。 仿佛代表著計算機對世界說出來的第一句話,因為它簡潔實用,所以被作為入門程序廣泛使用。 Java程序開發三步驟:編…

[轉載] Java中的命名參數

參考鏈接: Java命名約定 創建具有許多參數的方法是一個主要的缺點。 每當需要創建這樣的方法時,就在空氣中聞一聞:這是代碼的味道。 強化單元測試,然后進行重構。 沒有借口,沒有屁股。 重構! 使用構建器模…

[轉載] JVM(一):JVM體系結構詳解

參考鏈接: JVM如何工作–JVM體系結構 JVM簡介 JVM是Java程序得以運行的平臺,也是Java程序可以跨平臺的底層支撐,從整體上來看,JVM的主要功能可以分為加載和執行兩大塊。其中類加載器負責.class文件的尋址與加載&#xff0…

數據庫連接池的設計思路及java實現

2019獨角獸企業重金招聘Python工程師標準>>> connectionPool.DBConnectionManager [java] view plain copy package connectionPool; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; import java.sql.SQLException; i…

[轉載] java虛擬機 jvm 出入java棧 棧空間內存分配

參考鏈接: Java虛擬機(JVM)堆棧區域 java棧空間是一塊線程私有的內存空間,java堆和程序數據密切相關,那么java棧就是和線程執行密切相關。線程最基本的執行行為就是函數的調用。每次函數調用其實是通過java棧傳遞數據的。 數據結構中的棧的…

SVN命令行更新代碼

命令列表 svn help查看幫助信息 Available subcommands: add auth blame (praise, annotate, ann) cat changeli…

[轉載] Java中Runtime的使用

參考鏈接&#xff1a; Java中的JVM的關閉掛鉤 1 JDK中Runtime的定義 http://blog.csdn.net/lysnow_oss/archive/2007/05/12/1606349.aspx <轉載> 那就首先說點Runtime類吧&#xff0c;他是一個與JVM運行時環境有關的類&#xff0c;這個類是Singleton的。我…

窄帶物聯網(NB-IoT)初步了解

哪有什么天生如此&#xff0c;只是我們天天堅持。既然總有人要贏的話&#xff0c;為什么不能是我呢&#xff1f;[TOC] 什么是NB-Iot? 基于蜂窩的窄帶物聯網&#xff08;Narrow Band Internet of Things, NB-IoT&#xff09;成為萬物互聯網絡的一個重要分支。NB-IoT構建于蜂窩網…

ai人工智能_人工智能能力問答中的人工智能不確定性

ai人工智能1) Which of the following is true with respect to uncertainty in AI systems? Uncertainty arises when we are not 100 percent confident in our decisionsWhenever uncertainty arises, there is needs to be an estimation taken for getting to any conclu…

[轉載] 弄懂JDK、JRE和JVM到底是什么

參考鏈接&#xff1a; JDK JRE和JVM之間的區別 首先是JDK JDK(Java Development Kit) 是 Java 語言的軟件開發工具包(SDK)。 在JDK的安裝目錄下有一個jre目錄&#xff0c;里面有兩個文件夾bin和lib&#xff0c;在這里可以認為bin里的就是jvm&#xff0c;lib中則是jvm工作所需要…

mcq 隊列_人工智能搜索問題能力問題解答(MCQ)

mcq 隊列1) The main Aim of the AI system is to provide a solution for real-life problems by acting and thinking humanly. Whenever an agent is confronted by a problem, what is the first step that it follows towards searching a solution to the problem? Sear…

JavaOne大事紀:IBM談OpenJ9和Open Liberty

JavaOne大會以IBM陳述其最近對開源社區的貢獻作為開場&#xff1a;OpenJ9、Open Liberty和MicroProfile。IBM杰出工程師John Duimovich做了“IBM和Java&#xff1a;助力下一代創新”的開場演講。\\讀者可以回看演講視頻。\\Duimovich說IBM之所以致力于推動Java生態系統的創新&a…

[轉載] JVM中對象的回收過程

參考鏈接&#xff1a; JVM是否創建Main類(具有main()的類)的對象 當我們的程序開啟運行之后就&#xff0c;就會在我們的java堆中不斷的產生新的對象&#xff0c;而這是需要占用我們的存儲空間的&#xff0c;因為創建一個新的對象需要分配對應的內存空間&#xff0c;顯然我的內…

c語言格式對齊填充_C ++中類的大小 課堂上的填充和對齊| 派生類的大小

c語言格式對齊填充Prerequisite: 先決條件&#xff1a; sizeof() operator in C/C C / C 中的sizeof()運算符 Size of struct in C C中的struct大小 We know that a struct size is not only the summation of all the data members, rather its the minimum sum guaranteed. …

ELK系列~對fluentd參數的理解

這段時候一直在研究ELK框架&#xff0c;主要集成在對fluentd和nxlog的研究上&#xff0c;國內文章不多&#xff0c;主要看了一下官方的API&#xff0c;配合自己的理解&#xff0c;總結了一下&#xff0c;希望可以幫到剛入行的朋友們&#xff01; Fluentd&#xff08;日志收集與…

[轉載] Java中的50個關鍵字

參考鏈接&#xff1a; Java平臺如何獨立 Java中的50個關鍵字 關鍵字也稱為保留字&#xff0c;是指java語言中規定了特定含義的標示符。對于保留字&#xff0c;用戶只能按照系統規定的方式使用&#xff0c;不能自行定義。Java中有50個常用關鍵字&#xff1a; 與數據類型相關…

MySQL 直接存儲圖片并在 html 頁面中展示,點擊下載

數據庫實體類&#xff1a; package com.easy.kotlin.picturecrawler.entityimport java.util.* import javax.persistence.*Entity Table(indexes arrayOf(Index(name "idx_url", unique true, columnList "url"),Index(name "idx_category"…

css 文本背景色透明_如何使用CSS將文本或圖像的背景設置為透明?

css 文本背景色透明Introduction: 介紹&#xff1a; In web development, there are numerous ways by which we can style our websites or web pages. You can make use of lots of properties for creating attractive and responsive websites. 在Web開發中&#xff0c;我…

[轉載] 1.1Java使用JDBC原生方式連接MySql數據庫

參考鏈接&#xff1a; Java數據庫連接JDBC驅動程序 前言&#xff1a;今天有朋友問我原生的java連接數據庫&#xff0c;因為框架的使用&#xff0c;如果基礎不牢固的人&#xff0c;是很容易遺忘原生的連接方式。今天正好趁此做一下回顧&#xff1a; 這里只考慮原生方式&#x…

maven安裝及集成myeclipse

第一步&#xff1a;下載和安裝 1、官網下載Maven&#xff1a;http://maven.apache.org/download.cgi 2、解壓到一個文件夾2、設置環境變量&#xff1a;如&#xff1a;M2_HOME&#xff1a;D:\JAVA\apache-maven-3.0.5在path中添加;%M2_HOME%\bin;第二步&#xff1a;和MyEclipse集…