# @zohodesk/normalizer

> Normalizes JSON according to schema for Redux and Flux applications

Latest version **1.0.2** (published 2021-11-27) · MIT license · 0 weekly downloads

## Install

```sh
npm install @zohodesk/normalizer
pnpm add @zohodesk/normalizer
yarn add @zohodesk/normalizer
bun add @zohodesk/normalizer
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.0.2 |
| Published | 2021-11-27 |
| First published | 2019-12-10 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 2 |
| Unpacked size | 22.1 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | Vimal |
| Maintainers | ganeshkumar.m, zohosupport, vimalesan, vasikaran, skumaresan, kathiresan.r, jesinth, sriramamoorthy, lingam, sivanesh_s, vimalchandhru, ponkumar.s, sudalaimuthu, iniankarthick, johnson_raavanan, ksamy2020, kumaresanm, villuvicky, indragith, paripukazhenthi |
| Keywords | flux, normalize, api, json |

## Links

- npm: https://www.npmjs.com/package/@zohodesk/normalizer
- Repository: https://zgit.csez.zohocorpin.com/zohodesk/normalizer
- Issues: https://zgit.csez.zohocorpin.com/zohodesk/normalizer/issues
- npm.io page: https://npm.io/package/@zohodesk/normalizer

## Dependencies (2)

- [lodash](https://npm.io/package/lodash.md) ^4.11.2
- [selectn](https://npm.io/package/selectn.md) ^1.0.20

## Alternatives

- [@mapbox/jsonlint-lines-primitives](https://npm.io/package/@mapbox/jsonlint-lines-primitives.md) — 5.3M weekly downloads
- [reftools](https://npm.io/package/reftools.md) — 3.5M weekly downloads
- [@hey-api/openapi-ts](https://npm.io/package/@hey-api/openapi-ts.md) — 3.5M weekly downloads
- [@mapbox/geojson-rewind](https://npm.io/package/@mapbox/geojson-rewind.md) — 2.4M weekly downloads
- [turbo-stream](https://npm.io/package/turbo-stream.md) — 1.7M weekly downloads

## Recent versions

- 1.0.2 (latest) — 2021-11-27
- 1.0.0-exp.1 (experimental-version) — 2020-12-18
- 1.0.1 — 2021-01-11
- 1.0.0 — 2019-12-10

## README

# normalizr [![Build Status](https://travis-ci.org/vimalceg/normalizr.svg?branch=master)](https://travis-ci.org/vimalceg/normalizr)

Normalizes deeply nested JSON API responses according to a schema for [Flux](https://facebook.github.io/flux) and [Redux](http://rackt.github.io/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](https://github.com/facebook/flux) or [Redux](http://rackt.github.io/redux);
* You noticed [it's hard](https://groups.google.com/forum/#!topic/reactjs/jbh50-GJxpg) 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



```javascript
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
```javascript
{
  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

```javascript
import { normalize, schema, arrayOf } from 'normalizr';
```

First, define a schema for our entities:
Simple Schema
```javascript
const schema = require('simple-normalizr').schema;
const contactSchema = schema('contacts');
```

Then we define nesting rules:

Nested Schema
```javascript
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:

```javascript
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.  

```javascript
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.  

```javascript
const account = schema('accounts');
const contact = schema('contacts',{mapping:{account:account}});

```

### `arrayOf(schema)`

Describes an array of the schema passed as argument.

```javascript
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

```javascript
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](https://github.com/gaearon/normalizr/blob/a0931d7c953b24f8f680b537b5f23a20e8483be1/test/index.js#L89-L200) and the [discussion](https://github.com/gaearon/normalizr/issues/10) 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](https://github.com/gaearon/normalizr/blob/47ed0ecd973da6fa7c8b2de461e35b293ae52047/test/index.js#L132-L197) and the [discussion](https://github.com/gaearon/normalizr/issues/34) 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](http://github.com/gaearon)

---
_Source: https://npm.io/package/@zohodesk/normalizer · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
