微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

normalizr:合并对象结构不匹配的对象

如何解决normalizr:合并对象结构不匹配的对象

在大多数情况下,normalizr 已按预期设置架构和使用对象 ID。

为简洁起见,将省略从 API 返回的大部分内容,并尝试制作一个简单的示例。返回的是工作区,它们是包含创建工作区的用户和与该工作区共享的用户的对象。添加 role 对象只是为了说明该架构如何按预期工作。

共享对象和 createdBy 用户需要合并,但不太确定如何完成此操作。虽然共享对象有一个指向用户实体的指针。

使用 mergeStrategy 进行了一些尝试,但未能产生理想的结果,并且不太确定如何前进。

响应数据示例:

[
  {
    id: string,createdBy: { id: GUID,userName: string }
    role: { id: number,roleName: string }
    sharing: [
      {
        id: number,userId: GUID,(same as createdBy GUID)
        emailAddress: string,(same as createdBy userName)
        role: { id: number,roleName: string }
      }
    ]
  }
]

架构:

为简洁起见,不包括任何实验,仅包括目前有效的内容

const user = new schema.Entity('users');
const role = new schema.Entity('roles');
const sharing = new schema.Entity('sharing',{
  role,user: user,});

const workspaceSchema = new schema.Entity('workspaces',{
  createdBy: user,role,sharing: [sharing],});

const workspaceListSchema = new schema.Array(workspaceSchema);

原始数据:

[
  {
    id: 12345,role: { id: 1,roleName: "foo" }
    createdBy: {
      id: 123,userName: "foo@bar.com"
    },sharing: [
      {
       id: 789,userId: 123,emailAddress: "foo@bar.com"
       role: { id: 1,roleName: "foo" }
      }
    ]
  },{
    id: 67890,role: { id: 2,roleName: "bar" }
    createdBy: {
      id: 456,userName: "bar@foo.com"
    },sharing: [
      {
       id: 890,userId: 456,emailAddress: "bar@foo.com"
       role: { id: 2,roleName: "bar" }
      }
    ]
  }
]

标准化数据:

{
  entities: {
    users: {
      123: { id: 123,userName: "foo@bar.com"}
      456: { id: 456,userName: "bar@foo.com"}
    },roles: {
      1: { id: 1,roleName: 'foo' }
      2: { id: 2,roleName: 'bar' }
    },sharing: {
      789: { 
        id: 789,emailAddress: "foo@bar.com",role: 1,},890: { 
        id: 890,emailAddress: "bar@foo.com"
        role: 2,workspaces: {
      12345: {
        createdBy: "123",sharing: [789,890,...]
      },67890: {
        createdBy: "456",role: 2,sharing: [...]
      }
    }
  }
  result: [...workspace ids...]
}

预期结果:

理想情况下,希望共享对象具有基于 GUID 的单个用户指针,并将用户对象合并到 emailAddress 属性中:

entities: {
  sharing: {
   789: { 
     id: 789,user: 123,}
  users: {
    123: { 
      id: 123,userName: "foo@bar.com",}
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。