Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux normalizr - nested API responses

How can I use normalizr to deal with nested standardised JSON API responses that are key via the { data: ... } standard?

For example a Book

{
    data: {
        title: 'Lord of the Rings',
        pages: 9250,
        publisher: {
            data:  {
                name: 'HarperCollins LLC',
                address: 'Big building next to the river',
                city: 'Amsterdam'
            },
        },
        author: {
            data: {
                name: 'J.R.R Tolkien',
                country: 'UK',
                age: 124,
            }
        }
    }
}   

How would I design schemas to deal with the nested data key?

like image 636
AndrewMcLagan Avatar asked Jul 01 '16 13:07

AndrewMcLagan


1 Answers

For each entity in your response, you should create it's own schema.

In your example, we have three entities - books, authors and publishers:

// schemas.js
import { Schema } from 'normalizr';

const bookSchema = new Schema('book');
const publisherSchema = new Schema('publisher');
const authorSchema = new Schema('author');

If some entity contains nested data which should be normalized, we need to use define method of it schema.This method accepts an object with nesting rules.

If we need to normalize publisher and author props of book entity, we should pass an object to define function with same structure as our response:

// schemas.js
bookSchema.define({
  data: {
    publisher: publisherSchema,
    author: authorSchema
  }
});

Now we can normalize our response:

import { normalize } from 'normalizr';
import { bookSchema } from './schemas.js';

const response = {
    data: {
        title: 'Lord of the Rings',
        pages: 9250,
        publisher: {
            data:  {
                name: 'HarperCollins LLC',
                address: 'Big building next to the river',
                city: 'Amsterdam'
            },
        },
        author: {
            data: {
                name: 'J.R.R Tolkien',
                country: 'UK',
                age: 124,
            }
        }
    }
}

const data = normalize(response, bookSchema);
like image 97
1ven Avatar answered Oct 13 '22 01:10

1ven