Normalizes deeply nested JSON API responses according to a schema for Flux and Redux apps.
Kudos to Jing Chen for suggesting this approach.
Installation
npm install --save normalizr
Sample App
Flux
See flux-react-router-example.
Redux
See redux/examples/real-world.
The Problem
- You have a JSON API that returns deeply nested objects;
- You want to port your app to Flux or Redux;
- You noticed it's hard for Stores (or Reducers) to consume data from nested API responses.
Normalizr takes JSON and a schema and replaces nested entities with their IDs, gathering all entities in dictionaries.
For example,
id: 1 title: 'Some Article' author: id: 1 name: 'Dan' id: 2 title: 'Other Article' author: id: 1 name: 'Dan'
can be normalized to
result: 1 2 entities: articles: 1: id: 1 title: 'Some Article' author: 1 2: id: 2 title: 'Other Article' author: 1 users: 1: id: 1 name: 'Dan'
Note the flat structure (all nesting is gone).
Features
- Entities can be nested inside other entities, objects and arrays;
- Combine entity schemas to express any kind of API response;
- Entities with same IDs are automatically merged (with a warning if they differ);
- Allows using a custom ID attribute (e.g. slug).
Usage
;
First, define a schema for our entities:
const article = 'articles';const user = 'users';
Then we define nesting rules:
article;
Now we can use this schema in our API response handlers:
const ServerActionCreators = // These are two different XHR endpoints with different response schemas. // We can use the schema objects defined earlier to express both of them: { // Here, the response is an object containing data about one article. // Passing the article schema as second parameter to normalize() lets it // correctly traverse the response tree and gather all entities: // BEFORE: // { // id: 1, // title: 'Some Article', // author: { // id: 7, // name: 'Dan' // }, // contributors: [{ // id: 10, // name: 'Abe' // }, { // id: 15, // name: 'Fred' // }] // } // // AFTER: // { // result: 1, // <--- Note object is referenced by ID // entities: { // articles: { // 1: { // author: 7, // <--- Same happens for references to // contributors: [10, 15] // <--- other entities in the schema // ...} // }, // users: { // 7: { ... }, // 10: { ... }, // 15: { ... } // } // } // } response = ; AppDispatcher; } { // Here, the response is an object with the key 'articles' referencing // an array of article objects. Passing { articles: arrayOf(article) } as // second parameter to normalize() lets it correctly traverse the response // tree and gather all entities: // BEFORE: // { // articles: [{ // id: 1, // title: 'Some Article', // author: { // id: 7, // name: 'Dan' // }, // ... // }, // ... // ] // } // // AFTER: // { // result: { // articles: [1, 2, ...] // <--- Note how object array turned into ID array // }, // entities: { // articles: { // 1: { author: 7, ... }, // <--- Same happens for references to other entities in the schema // 2: { ... }, // ... // }, // users: { // 7: { ... }, // .. // } // } // } response = ; AppDispatcher; }
Finally, different Stores can tune in to listen to all API responses and grab entity lists from action.response.entities
:
AppDispatcher;
API Reference
new Schema(key, [options])
Schema lets you define a type of entity returned by your API.
This should correspond to model in your server code.
The key
parameter lets you specify the name of the dictionary for this kind of entity.
const article = 'articles'; // You can use a custom id attributeconst article = 'articles' idAttribute: 'slug' ; // Or you can specify a function to infer it { /* ... */ }const article = 'articles' idAttribute: generateSlug ; // You can also specify meta properties to be used for customizing the output in assignEntity (see below)const article = 'articles' idAttribute: 'slug' meta: removeProps: 'publisher' ;
Schema.prototype.define(nestedSchema)
Lets you specify relationships between different entities.
const article = 'articles';const user = 'users'; article;
Schema.prototype.getKey()
Returns the key of the schema.
const article = 'articles'; article;// articles
Schema.prototype.getIdAttribute()
Returns the idAttribute of the schema.
const article = 'articles';const slugArticle = 'articles' idAttribute: 'slug' ; article;// idslugArticle;// slug
Schema.prototype.mappedBy(foreignKey)
This method permits to link a Schema property with a foreign property in another one Schema.
const project = 'projects';const user = 'users'; project; user;
This way, the relations will always be consistent. If you get this response for a user :
{
id: 1,
projects: [1, 2],
}
Normalizr will give you this :
result: 1 entities: users: 1: id: 1 projects: 1 2 projects: 1: id: 1 collaborators: 1 2: id: 1 collaborators: 1
Using this property is completely optional and you can even chose to use it only on one side of the relationship.
arrayOf(schema, [options])
Describes an array of the schema passed as argument.
const article = 'articles';const user = 'users'; article;
If the array contains entities with different schemas, you can use the schemaAttribute
option to specify which schema to use for each entity:
const article = 'articles';const image = 'images';const video = 'videos';const asset = images: image videos: video; // You can specify the name of the attribute that determines the schemaarticle; // Or you can specify a function to infer it { /* ... */ }article;
valuesOf(schema, [options])
Describes a map whose values follow the schema passed as argument.
const article = 'articles';const user = 'users'; article;
If the map contains entities with different schemas, you can use the schemaAttribute
option to specify which schema to use for each entity:
const article = 'articles';const user = 'users';const group = 'groups';const collaborator = users: user groups: group; // You can specify the name of the attribute that determines the schemaarticle; // Or you can specify a function to infer it { /* ... */ }article;
unionOf(schemaMap, [options])
Describe a schema which is a union of multiple schemas. This is useful if you need the polymorphic behavior provided by arrayOf
or valuesOf
but for non-collection fields.
Use the required schemaAttribute
option to specify which schema to use for each entity.
const group = 'groups';const user = 'users'; // a member can be either a user or a groupconst member = users: user groups: group; // You can specify the name of the attribute that determines the schemagroup; // Or you can specify a function to infer it { /* ... */ }group;
A unionOf
schema can also be combined with arrayOf
and valueOf
with the same behavior as each supplied with the schemaAttribute
option.
const group = 'groups';const user = 'users'; const member = ; group;
normalize(obj, schema, [options])
Normalizes object according to schema.
Passed schema
should be a nested object reflecting the structure of API response.
You may optionally specify any of the following options:
-
assignEntity
(function): This is useful if your backend emits additional fields, such as separate ID fields, you'd like to delete in the normalized entity. See the tests and the discussion for a usage example. -
mergeIntoEntity
(function): You can use this to resolve conflicts when merging entities with the same key. See the test and the discussion for a usage example.
const article = 'articles';const user = 'users'; article; // ... // Normalize one article objectconst json = id: 1 author: ... ;const normalized = ; // Normalize an array of article objectsconst arr = id: 1 author: ... ...const normalized = ; // Normalize an array of article objects, referenced by an object key:const wrappedArr = articles: id: 1 author: ... ... const normalized = ;
Explanation by Example
Say, you have /articles
API with the following schema:
articles: article*
article: {
author: user,
likers: user*
primary_collection: collection?
collections: collection*
}
collection: {
curator: user
}
Without normalizr, your Stores would need to know too much about API response schema.
For example, UserStore
would include a lot of boilerplate to extract fresh user info when articles are fetched:
// Without normalizr, you'd have to do this in every store: AppDispatcher;
Normalizr solves the problem by converting API responses to a flat form where nested entities are replaced with IDs:
result: 12 10 3 ... entities: articles: 12: authorId: 3 likers: 2 1 4 primaryCollection: 12 collections: 12 11 ... users: 3: name: 'Dan' 2: ... 4: ... collections: 12: curator: 2 name: 'Stuff' ...
Then UserStore
code can be rewritten as:
// With normalizr, users are always in action.response.entities.users AppDispatcher;
Dependencies
- Some methods from
lodash
, such asisObject
,isEqual
andmapValues
Browser Support
Modern browsers with ES5 environments are supported.
The minimal supported IE version is IE 9.
Running Tests
git clone https://github.com/gaearon/normalizr.git
cd normalizr
npm install
npm test # run tests once
npm run test:watch # run test watcher