Search code examples
javascriptnormalizr

normalizr schema - child reference parent


Trying to get to grips with normalizr, data structure and schema shown below:

const data = {
    "name": "abc",
    "outlet": [
        {
            "id": 1,
            "retailer": {
                "id": 1
            }
        },
        {
            "id": 2,
            "retailer": {
                "id": 1
            }
        }
    ]
}

const retailerSchema = new schema.Entity('retailers');

const outletSchema = new schema.Entity('outlets', {
    retailer: retailerSchema
});

const normalized = normalize(data, {
    retailers: [retailerSchema],
    outlets: [outletSchema]
})

Current result:

normalized.result == {name: "abc", outlets: [1, 2]}
normalized.entities.retailers == {1: {id: 1}}
normalized.entities.outlets == {1: {id: 1, retailer: 1}, 2: {id: 2, retailer: 1}}

Is it possible to add outlet references based on unique retailers? e.g.

normalized.result == {name: "abc", outlets: [1, 2], retailers: [1]}
normalized.entities.retailers == {1: {id: 1, outlets: [1, 2]}}
normalized.entities.outlets == {1: {id: 1, retailer: 1}, 2: {id: 2, retailer: 1}}

Solution

  • Is it possible to add outlet references based on unique retailers?

    Not really. The result that Normalizr returns is always in the same format of the input data. Since your data is { name, outlet }, those are the only keys that will exist in the result output.

    If you had a unique identifier on the top-level object (the whole data structure), you could make use of the processStrategy for schema.Entity and shuffle things around, but this is really not recommended.