normalizr API

API

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 entity
    processStrategy: (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' }
  }
}复制代码



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值