Normalizr - 它是一种为非 ID 实体模型生成 ID 的方法吗?

Normalizr - is it a way to generate IDs for non-ids entity model?

我正在使用 normalizr 实用程序处理基于非 ID 模型的 API 响应。据我所知,通常 normalizr 使用 ids 模型,但也许有某种方法可以生成 ids "on the go"?

我的API响应示例:

```

// input data:
const inputData = {
  doctors: [
   {
    name: Jon,
    post: chief
   },
   {
    name: Marta,
    post: nurse
   },
   //....
}

// expected output data:
const outputData = {
  entities: {
   nameCards : {
    uniqueID_0: { id: uniqueID_0, name: Jon, post: uniqueID_3 },
    uniqueID_1: { id: uniqueID_1, name: Marta, post: uniqueID_4 }
   },
   positions: {
    uniqueID_3: { id: uniqueID_3, post: chief },
    uniqueID_4: { id: uniqueID_4, post: nurse }
   }
  },
  result: uniqueID_0
}

```

P.S。 我从某人那里听说在 normalizr 中为像我这样的情况生成 ID "by the hood",但我确实找到了这样的解决方案。

有一个 processStrategy,它基本上是一个函数,在该函数中分配你的 id,即。 value.id = uuid()。访问下面的 link 以查看示例 https://github.com/paularmstrong/normalizr/issues/256

如本文所述issue

Normalizr is never going to be able to generate unique IDs for you. We don't do any memoization or anything internally, as that would be unnecessary for most people.

Your working solution is okay, but will fail if you receive one of these entities again later from another API endpoint.

My recommendation would be to find something that's constant and unique on your entities and use that as something to generate unique IDs from.

然后,如文档中所述,您需要设置 idAttribute 以将 'id' 替换为另一个密钥:

const data = { id_str: '123', url: 'https://twitter.com', user: { id_str: '456', name: 'Jimmy' } };

const user = new schema.Entity('users', {}, { idAttribute: 'id_str' });
const tweet = new schema.Entity('tweets', { user: user }, { 
    idAttribute: 'id_str',
    // Apply everything from entityB over entityA, except for "favorites"
    mergeStrategy: (entityA, entityB) => ({
      ...entityA,
      ...entityB,
      favorites: entityA.favorites
    }),
    // Remove the URL field from the entity
    processStrategy: (entity) => omit(entity, 'url')
});

const normalizedData = normalize(data, tweet);

编辑

您始终可以使用外部库或手动提供唯一 ID:

inputData.doctors = inputData.doctors.map((doc, idx) => ({ 
  ...doc, 
  id: `doctor_${idx}`
}))