Defining your schema

To make redux-db normalize your nested data, you must define a schema. Given the following data:

const blogPosts = [
    {
        id: "post1",
        author: { username: "user1", name: "User 1" },
        body: "......",
        comments: [
            {
                id: "comment1",
                author: { username: "user2", name: "User 2" },
                comment: "....."
            },
            {
                id: "comment2",
                author: { username: "user3", name: "User 3" },
                comment: "....."
            }
        ]
    },
    {
        id: "post2",
        author: { username: "user2", name: "User 2" },
        body: "......",
        comments: [
            {
                id: "comment3",
                author: { username: "user1", name: "User 1" },
                comment: "....."
            }
        ]
    }
]

You would define a schema like so:

/// schema.js

import * as ReduxDB from "redux-db";

const schema = {
    User: {
        username: { type: "PK" }
    },
    BlogPost: {
        id: { type: "PK" },
        author: { references: "User", relationName: "posts" }
    },
    Comment: {
        id: { type: "PK" },
        post: { references: "BlogPost", relationName: "comments" },
        author: { references: "User", relationName: "comments" }
    }
};

export const db = ReduxDB.createDatabase(schema);

Note you may only define foreign and primary keys. The data fields like “User.name” and “Comment.comment” are not needed in the schema.

Using this schema definition, the example data would be normalized out in the following manner:

const normalizedData = {
    User: {
        ids: ["user1", "user2", "user3"],
        byId: {
            "user1": {
                username: "user1",
                name: "User 1"
            },
            "user2": {
                username: "user2",
                name: "User 2"
            }
        }
    },
    BlogPost: {
        ids: ["post1", "post2"],
        byId: {
            "post1": {
                id: "post1",
                author: "user1",
                body: "....."
            },
            "post2": {
                id: "post2",
                author: "user2",
                body: "....."
            }
        }
    },
    Comment: {
        ids: ["comment1", "comment3"],
        byId: {
            "comment1": {
                id: "comment1",
                post: "post1",
                author: "user2",
                comment: "....."
            },
            "comment3": {
                id: "comment3",
                post: "post2",
                author: "user1",
                comment: "....."
            }
        }
    }
}