且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Normalizr - 如何生成与父实体相关的slug / id

更新时间:2023-12-05 23:37:46

问题



以你显示的方式使用uuid将无效。

Problem

Using uuid the way you show will not work.

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

uuid.v4()返回一个字符串, idAttribute 的可接受值,但现在所有图像将拥有相同的uid。不是你想要的。

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

理想情况下这可行:

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

不幸的是, idAttribute 将被多次调用,如上所述在本期中。这将破坏任何实体关系。在您的示例中,图像将具有与用户实体引用它们不同的uid。

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.

示例输出:

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'
  }
};



解决方案



解决此问题是改变 processStrategy 回调中的输入值,给它一个 uid 属性。

Solution

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

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

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

你现在正在改变这个值,所以很糟糕,但 idAttribute 选项使用输入值,而不是处理后的值。

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

或者,您可以改变 idAttribute 回调,然后你不会将 uid 字段添加到输出值。

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

旁注:我建议使用 cuid npm包而不是 uuid

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