如何使用 Normalizr 为递归模型定义模式

How to define schema for recursive model with Normalizr

在尝试规范化负载时遇到一些问题,该负载包含与使用 Normalizr

的父级相同类型的嵌套模式

例如,我有一个初始对象 (menu),它有一个子对象 (sections),它是一个对象数组 (section),可以很深。

{
  id: 123,
  sections: [{
    id: 1,
    sections:[{ id: 4, sections: [ id: 5, sections: [] ] }]
  }, {
    id: 2,
    sections:[]
  }, {
    id: 3,
    sections:[]
  }]
}

我首先创建了一个 menu 模式,该模式在定义中包含链接到 sections 模式的部分,该模式适用于第一遍,但随后无法处理部分的子部分,所以我在 section 模式中添加了一个具有相同名称的后续定义(值得一试),但它没有用。

const section = new schema.Entity('sections')

const sections = new schema.Entity('sections', {
  sections: section
})

const menu = new schema.Entity('menu', { 
  sections: [ sections ]
})

section.define({ sections })

我希望以下面的对象结束:

{
  entities: {
    menu: {
      sections: [1, 2, 3]
    },
    sections: [{
      1: { id: 1, sections: [4] },
      2: { id: 2, sections: [] },
      3: { id: 3, sections: [] },
      4: { id: 4, sections: [5] },
      5: { id: 5, sections: [] },
    }]
  }
}

您的 sections 架构应该是 Array

const section = new schema.Entity('sections')
const sections = new schema.Array(section);
section.define({ sections });
const menu = new schema.Entity('menu', { sections });

然后,在使用中...

const data = {
  id: 123,
  sections: [{
    id: 1,
    sections:[{ id: 4, sections: [ { id: 5, sections: [] } ] }]
  }, {
    id: 2,
    sections:[]
  }, {
    id: 3,
    sections:[]
  }]
};

normalize(data, menu)

会 return:

{
  "entities": {
    "sections": {
      "1": { "id": 1, "sections": [ 4 ] },
      "2": { "id": 2, "sections": [] }, 
      "3": { "id": 3, "sections": [] },
      "4": { "id": 4, "sections": [ 5 ] },
      "5": { "id": 5, "sections": [] }
    },
    "menu": {
      "123": { "id": 123, "sections": [ 1, 2, 3 ] }
    }
  },
  "result": 123
}

如果有人有相同 "type" 的嵌套对象的情况,例如 "sections" 并且顶级结构也是 "sections" 的数组,如下所示:

const data = [
    {
      id: 1,
      sections:[{ id: 4, sections: [ { id: 5, sections: [] } ] }]
    }, 
    {
      id: 2,
      sections:[]
    }, 
    {
      id: 3,
      sections:[]
    }
  ]

这是"unnest"他们的一种方式:

import {schema, normalize} from "normalizr";

const child = new schema.Entity("sections");
const sections = new schema.Array(child);
child.define({sections});

const topLevel = new schema.Entity("sections", {
    sections
});

const customSchema = [topLevel];

console.log(normalize(data, customSchema));

您将得到的是:

{
   "entities":{
      "sections":{
         "1":{
            "id":1,
            "sections":[
               4
            ]
         },
         "2":{
            "id":2,
            "sections":[

            ]
         },
         "3":{
            "id":3,
            "sections":[

            ]
         },
         "4":{
            "id":4,
            "sections":[
               5
            ]
         },
         "5":{
            "id":5,
            "sections":[

            ]
         }
      }
   },
   "result":[
      1,
      2,
      3
   ]
}