Search code examples
normalizr

How to get a reference to the nested entities in normalizr?


I'm normalizing a one level nested list of lots. Where the first level lots are called masters nested ones are slaves.

// my schema
const lot = new schema.Entity('lots');
const lots = new schema.Array(lot);
lot.define({slaves: lots});

// my data
const list = [
  {
    id: 1,
    name: 'Lot #1',
    slaves: [
      {
        id: 2,
        name: 'Lot #2'
      }
    ]
  }, {
    id: 4,
    name: 'Lot #4',
    slaves: []
  }
];

normalize(list, lots);

And I get this:

{
  entities : {
    lots: {
      '1': {
        id: 1,
        name: 'Lot #1',
        slaves: [2]
      },
      '2': {
        id: 2,
        name: 'Lot #2'
      },
      '4': {
        id: 4,
        name: 'Lot #4',
        slaves: []
      }
    }
  },
  result : [1, 4]
}

There's anything wrong with it. But I would like to add some more stuff to the normalized result and I don't know how.

  • Have the master lot id on the normalized slaves
  • An array of slaves id's also on the result

So the previous example will be normalized like this:

{
  entities : {
    lots: {
      '1': {
        id: 1,
        name: 'Lot #1',
        slaves: [2]
      },
      '2': {
        id: 2,
        name: 'Lot #2',
        master: 1
      },
      '4': {
        id: 4,
        name: 'Lot #4',
        slaves: []
      }
    }
  },
  result : {
    masters: [1, 4],
    slaves: [2],
  }
}

Is this possible with normalizr?


Solution

  • Have the master lot id on the normalized slaves

    This is definitely possible using a custom processEntity function. There's an example here. In short:

    const processStrategy = (value, parent, key) => ({
      ...value,
      master: key === 'slaves' ? parent.id : undefined
    });
    const lot = new schema.Entity('lots', { processStrategy });
    

    An array of slaves id's also on the result

    This is not possible. The result is always dependent on the entry schema passed to normalize.