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 (将#修改为@)