Normalizr - 如何处理已经规范化的嵌套实体

Normalizr - How to handle nested entities that are already normalized

我在非常嵌套的 JSON 中有实体,它们已经遵循 normalizr 格式,其中 idAttribute 已经是定义对象的键:

groups: [{
  id: 'foo',
  families: {
    smiths: {
      people: [{
        id: 'sam',
      }, {
        id: 'jake',
      }],
    },
    jones: {
      people: [{
        id: 'john',
      }, {
        id: 'sue',
      }],
    },
  },
}];

在此示例中,请注意 families 属性使用 id (smithsjones) 来标识 people 对象数组ids.

此模式可能如下所示:

const person = new Entity('person');
const family = new Entity('family', {
  people: [person],
}, {idAttribute: ???});
const group = new Entity('family', {
  family: [family],
});

问题:有没有办法指定模式的 idAttribute 是定义它的键?换句话说,我将如何定义 Family 的架构,因为它与 groupspeople 相关?

另一个问题,是否有办法 denormalize 扁平化状态,以便家庭 families: {[id]: obj} 模式与上面示例 json 中的模式保持一致?

Is there a way to specify that a schema's idAttribute is the key where it is defined?

是的。 idAttribute 函数有 3 个参数:valueparentkey。请阅读docs。在您的情况下,您可以使用 keyschema.Values

const family = new schema.Entity('families', { 
    people: [ person ] 
}, (value, parent, key) => key);
const families = new schema.Values(family);
const group = new schema.Entity('groups', {
    families
});

对于 denormalize,您需要为 family 使用单独的架构,因为 ID 无法从密钥派生。