问题描述
我正在使用normalizr
util来处理基于非ids模型的API响应.据我所知,通常normalizr
与ids模型一起使用,但是也许有某种方式可以随时随地"生成ids?
I'm using normalizr
util to process API response based on non-ids model. As I know, typically normalizr
works with ids model, but maybe there is a some way to generate 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,但我确实找到了这种解决方案.
P.S.I heard from someone about generating IDs "by the hood" in normalizr
for such cases as my, but I did found such solution.
推荐答案
此 issue :
您的工作解决方案可以,但是如果您收到以下其中一项,将会失败 这些实体稍后再从另一个API端点进行.
Your working solution is okay, but will fail if you receive one of these entities again later from another API endpoint.
我的建议是找到恒定的东西, 在您的实体上具有唯一性,并以此来产生独特性 来自的ID.
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':
And then, as mentioned in the docs, you need to set idAttribute
to replace 'id' with another key:
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:
You can always provide unique id's using external lib or by hand:
inputData.doctors = inputData.doctors.map((doc, idx) => ({
...doc,
id: `doctor_${idx}`
}))
这篇关于Normalizr-这是一种为非id实体模型生成ID的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!