npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@zohodesk/normalizer

v1.0.2

Published

Normalizes JSON according to schema for Redux and Flux applications

Downloads

1,409

Readme

normalizr Build Status

Normalizes deeply nested JSON API responses according to a schema for Flux and Redux apps.

Installation

npm install simple-normalizr --save

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, ##Assume SupportDesk scenario

  • each contact create multiple ticket
  • contact associate with one account
  • ticket has conversation. conversation has multiple threads and multiple comments
1. Denormalized Simple contact object
{
  id:"c1",
  name:"vimal"
}
2. Denormalized Array of Contact object
[
  {
    id:"c1",
    name:"vimal1"
  },
  {
    id:"c2",
    name:"vimal2"
  }
]

can be normalized to

  1. Normalized Simple contact
{
  result: "c1",
  entities: {
    contacts: {
      "c1": {
        id: 1,
        name:"vimal"
      }
    }
  },
  result:"c1"

}```

2. Normalized Array of Contact object
```javascript
{
  entities:{
    "contacts":{
      "c1":{
        id:"c1",
        name:"vimal1"
      },
      "c2":{
        id:"c2",
        name:"vimal2"
      }
    }
  },
  result:["c1","c2"]
}

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
  • Allows using a custom ID attribute (e.g. slug).

Usage

import { normalize, schema, arrayOf } from 'normalizr';

First, define a schema for our entities: Simple Schema

const schema = require('simple-normalizr').schema;
const contactSchema = schema('contacts');

Then we define nesting rules:

Nested Schema

const schema = require('simple-normalizr').schema;
const accountSchema = schema("accounts");
const contactSchema = schema("contacts",{mapping:{ account:accountSchema } });

Now we can use this schema in our API response:

const normalize = require('simple-normalizr').normalize;
const response={
  id:"c1",
  name:"vimal1",
  account:{
    id:"a1",
    aname:"account1"
  }
}
const normalizedContact = normalize(response, contact);

{
 entities:{
   "contacts":{
     "c1":{
       id:"c1",
       name:"vimal1",
       "account": "a1"
     }
   },
   "accounts":{
     "a1":{
       id:"a1",
       aname:"account1"
     }
   }
 },
 result:"c1"
}

API Reference

schema(entityName,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 contact = schema('contacts');

// You can use a custom id attribute
const contact = schema('contacts',{ id: 'contact_id' });

assignEntity
function customAssignEntity(obj){
  obj["newKey"]="newValue";
  return obj
}
const normalizedContact = normalize(response,
  schema("contacts",{ entityAssignment:customAssignEntity}))

{
entities:{
  "contacts":{
    "c1":{
      "contact_id": "c1",
      name:"vimal",
      "newKey":"vimal"
    }
  }
},
result:"c1"
}

Lets you specify relationships between different entities.

const account = schema('accounts');
const contact = schema('contacts',{mapping:{account:account}});

arrayOf(schema)

Describes an array of the schema passed as argument.

const arrayOf = require("simple-normalizr").arrayOf;
const ticket = schema('tickets');
const contact = schema('contacts',{mapping:{ticket:arrayOf(ticket)}});

If the array contains entities with different schemas

const thread = schema("threads");
const comment = schema("comments");
const ticket = schema("ticket",
  arrayOf(
    schema({
      union:{
        thread:thread,
        comment:comment
      },
      key:"type"
    })))

valuesOf(schema, [options])

--Describes a map whose values follow the schema passed as argument.(not yet done)

--If the map contains entities with different schemas, (not yet done)

normalize(obj, schema)

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 (not yet done) (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.

Dependencies

  • Some methods from lodash, such as isObject, isEqual and mapValues
  • selectn

Browser Support

Modern browsers with ES5 environments are supported.
The minimal supported IE version is IE 9.

Running Tests

git clone https://github.com/vimalceg/normalizr.git
cd normalizr
npm install
npm test # run tests once
npm run test:watch # run test watcher

Credits

Normalizr was originally created by Dan Abramov