Skip to content Skip to sidebar Skip to footer

Normalizr - How To Generate Slug/id Related To Parent Entity

How can I assign id/slug related to the entity's parent using normalizr? Example: API Response for a user call: { id: '12345', firstName: 'John', images: [ { url: '

Solution 1:

idAttribute can be a function that receives the entity, the parent and the key that references the slice of state:

const image = newSchema('images', {
  idAttribute: (entity, parent) =>`${parent.id}-${entity.name}`
});

Solution 2:

Problem

Using uuid the way you show will not work.

const image = new Schema('images', { idAttribute: uuid.v4() });

uuid.v4() returns a string, an acceptable value for idAttribute but now all your images will have the same uid. Not what you want.

Ideally this would work:

const image = newSchema('images', { idAttribute: () => uuid.v4() });

Unfortunately, idAttribute will be invoked multiple times, as mentioned in this issue. This will break any entity relations. In your example, the images will have different uids than what the user entity references them as.

example output:

users: {
  '12345': {
    id:'12345',
    firstName:'John',
    images: [
      "cj20qq7zl00053j5ws9enz4w6",
      "cj20q44vj00053j5wauawlr4u"
    ],
  }
};images: {
  cj20q44v100003j5wglj6c5h8: {
    url:'https://www.example.org/image0',
    name:'image0'
  },
  cj20q44vg00013j5whajs12ed: {
    url:'https://www.example.org/image1',
    name:'image1'
  }
};

Solution

A work around for this is to mutate the input value in the processStrategy callback, giving it an uid attribute.

constgetUid = value => {
  if (!Object.prototype.hasOwnProperty.call(value, 'uid')) value.uid = uuid.v4();
  return {...value};
};

const image = newSchema('images', { processStrategy: getUid, idAttribute: 'uid'});

You're mutating the value now, so that sucks, but the idAttribute option uses the input value, not the processed value.

Alternatively, you could mutate the value in the idAttribute callback, then you would not add the uid field to the output value.

sidenote: I would recommend using the cuid npm package instead of uuid

Post a Comment for "Normalizr - How To Generate Slug/id Related To Parent Entity"