Normalizr-这是一种为非id实体模型生成ID的方法吗? [英] Normalizr - is it a way to generate IDs for non-ids entity model?

查看:117
本文介绍了Normalizr-这是一种为非id实体模型生成ID的方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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 :

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

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.

您的工作解决方案可以,但是如果您收到以下其中一项,将会失败 这些实体稍后再从另一个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的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆