Normalizr-是否可以为非id实体模型生成ID?

时间:2018-09-11 10:28:04

标签: javascript reactjs normalizr

我正在使用Customer A B C D E F G H I J New_Customers 11/30/2015 1 0 1 0 0 1 1 0 0 0 4 12/31/2015 0 1 0 1 0 1 1 0 0 1 3 1/31/2016 0 0 0 0 0 1 1 0 0 1 0 2/29/2016 1 1 1 1 1 1 0 1 1 1 3 3/31/2016 1 1 0 1 1 0 1 1 0 1 0 4/30/2016 0 1 1 1 0 1 1 1 0 1 0 5/31/2016 1 1 1 1 1 1 0 1 0 1 0 util来处理基于非id模型的API响应。据我所知,通常normalizr可以使用ids模型,但是也许有一种“随时随地”生成id的方法?

我的API响应示例:

```

normalizr

```

P.S。 我听说有人在// 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 } 中针对诸如此类的情况“在后台”生成ID,但我确实找到了这种解决方案。

2 个答案:

答案 0 :(得分:2)

如本issue中所述:

  

Normalizr永远不会为您生成唯一的ID。我们   不要做任何记忆或内部任何事情,因为那样会   对于大多数人来说是不必要的。

     

您的工作解决方案可以,但是如果您收到以下其中一项,则将失败   这些实体稍后再从另一个API端点进行。

     

我的建议是找到恒定且   在您的实体上具有唯一性,并将其用作产生唯一性的方法   来自的ID。

然后,如文档中所述,您需要将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);

编辑

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

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

答案 1 :(得分:0)

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

相关问题