Coder Social home page Coder Social logo

ptzagk / denormalizr Goto Github PK

View Code? Open in Web Editor NEW

This project forked from gpbl/denormalizr

0.0 0.0 0.0 239 KB

Denormalize data normalized with normalizr

Home Page: https://www.npmjs.com/package/denormalizr

License: MIT License

JavaScript 100.00%

denormalizr's Introduction

denormalizr takes data and entities normalized by normalizr, and returns its complete tree โ€“ including nested entities.

This module is useful when consuming normalized data, e.g. in redux selectors. While normalizr is great on making data consistent between the app, reassembling entities can be a tedious work. Denormalizr can help!

npm version npm downloads build status Code Climate Coveralls

npm install denormalizr --save
import { denormalize } from "denormalizr";
const denormalized = denormalize(entity, entities, entitySchema);

Documentation

API

denormalize (entity, entities, schema) -> Object|Array|Immutable.Map|Immutable.List

Params

entity {Object|Array|Number|String|Immutable.Map|Immutable.List}

The entity to denormalize, its id, or an array of entities or ids.

entities {Object|Immutable.Map}

An object to entities used to denormalize entity and its referred entities.

entitySchema {schema.Entity}

The normalizr schema used to define entity.

Returns

The denormalized object (or Immutable.Map), or an array of denormalized objects (or an Immutable.List).

Examples

For the following examples, consider to have a JSON response from a REST API consisting in a list of articles, where each article has a author field.

{
  "articles": [{
    "id": 1,
    "title": "10 mindblowing reasons to prefer composition over inheritance",
    "author": {
      "id": 1,
      "name": "Dan"
    },
  }, {
    "id": 2,
    "title": "You won't believe what this high order component is doing",
    "author": {
      "id": 1,
      "name": "Dan"
    }
  }]
}

To normalize this response with normalizr, we can define two Schemas: articleSchema and authorSchema.

import { normalize, schema } from 'normalizr';

const articleSchema = new schema.Entity('articles');
const authorSchema = new schema.Entity('authors');
const articleList = new schema.Array(articleSchema);

articleSchema.define({
  author: authorSchema,
});

const normalized = normalize(response, {
  articles: articleList,
})

This way we have the usual normalized object with entities:

// content of normalized
{ entities: 
   { articles: 
      { '1': 
         { id: 1,
           title: '10 mindblowing reasons to prefer composition over inheritance',
           author: 1 },
        '2': 
         { id: 2,
           title: 'You won\'t believe what this high order component is doing',
           author: 1 } },
     authors: 
      { '1': 
         { id: 1, 
          name: 'Dan' } } },
  result: { articles: [ 1, 2 ] } }

Let say we want to display the articles with ids 1 and 2, and for each article its author.

In order to get the whole author object for each article, we need to loop over the author entities:

const articleIds = [1, 2];
const articles = articleIds.map(id => {
  const article = normalized.entities.articles[id];
  article.author = normalized.entities.authors[article.author];
})

We are basically reverting to the original JSON response. We are, indeed, denormalizing.

Without the need to know the entity's shapes, we can use denormalizr to simplify this process. Thus:

import { denormalize } from 'denormalizr';

const articles = denormalize([1,2], normalized.entities, articleList);

articles contains now the selected articles with the authors in them:

// console.log(articles)
[ { id: 1,
    title: '10 mindblowing reasons to prefer composition over inheritance',
    author: { id: 1, name: 'Dan' } },
  { id: 2,
    title: 'You won\'t believe what this high order component is doing',
    author: { id: 1, name: 'Dan' } } ]

denormalize() accepts as first parameter the entity we want to denormalize, which can be a single object, an array of object, a single id or an array of ids. The second parameter is the whole entities object, which is consumed when the entity schema (third parameter) has references to one or more entities.

Denormalize a single object

const article = normalized.entities.articles['1'];
const denormalized = denormalize(article, normalized.entities, articleSchema);
// console.log(denormalized)
{
  id: 1,
  title: 'Some Article',
  author: {
    id: 1,
    name: 'Dan'
  },
}

Denormalize a list of objects

const article1 = normalized.entities.articles['1'];
const article2 = normalized.entities.articles['2'];

const denormalized = denormalize([article1, article2], normalized.entities, articleListSchema);
// console.log(denormalized)
[{
  id: 1,
  title: '10 mindblowing reasons to prefer composition over inheritance',
  author: {
    id: 1,
    name: 'Dan'
  },
},{
  id: 2,
  title: 'You won\'t believe what this high order component is doing',
  author: {
    id: 1,
    name: 'Dan'
  },
}]

Denormalize by passing the id

const denormalized = denormalize(1, normalized.entities, articleSchema);
// console.log(denormalized);
{
  id: 1,
  title: '10 mindblowing reasons to prefer composition over inheritance',
  author: {
    id: 1,
    name: 'Dan'
  },
}

Denormalize by passing a list of ids

const denormalized = denormalize([1, 2], normalized.entities, articleListSchema);
// console.log(denormalized)
[{
  id: 1,
  title: '10 mindblowing reasons to prefer composition over inheritance',
  author: {
    id: 1,
    name: 'Dan'
  },
},{
  id: 2,
  title: 'You won\'t believe what this high order component is doing',
  author: {
    id: 1,
    name: 'Dan'
  },
}]

Recursive schemas

Denormalizr can handle circular references caused by recursive schemas (see #2).

For example, take these schemas, where articles have an author property containing a list of articles:

const articleSchema = new schema.Entity('articles');
const authorSchema = new schema.Entity('author');
const articleList = new schema.Array(articleSchema);

articleSchema.define({
  author: authorSchema,
});

authorSchema.define({
  articles: articleList,
});

const JSONResponse = {
  "articles": [{
    "id": 2,
    "title": "You won\'t believe what this high order component is doing",
    "author": {
      "id": 1,
      "name": 'Dan',
      "articles": [2],
    },
  }],
};

const normalized = normalize(JSONResponse, {
  articles: articleList,
});

const article = data.entities.articles['2'];
const denormalized = denormalize(article, data.entities, articleSchema);

console.log(denormalized.author.articles[0] === denormalized)); // true

Usage with Immutable

Denormalizr works well with immutable-js, however recursive schemas are not supported:

// This nested article contains only a reference to the author's id:
denormalized.author.articles[0].author === 1

Related work:

denormalizr's People

Contributors

gpbl avatar yorunohikage avatar just-boris avatar jeffcarbs avatar maximecony avatar brunolemos avatar cecigarcia avatar defusion avatar pierscowburn avatar tarjei avatar smilingpoplar avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.