如何将id数组添加到没有它们的实体

时间:2017-01-06 17:36:52

标签: redux normalizr

我的架构几乎完全按照我想要的方式设置在redux状态,除了我想在formTemplate对象中添加一个表单ID数组。 它看起来像这样:

// Normalized Form Templates
{
  1: {
    id: '1',
    isGlobal: true,
    name: 'Form Template Name',
    forms: [1, 2], // This is the line I want to add...but how?
  },
}

// Normalized Forms
{
  1: {
    id: '1',
    createdAt: '2016-12-28T23:30:13.547Z',
    name: 'Form 1',
    parentTemplate: '1',
    pdfs: [1, 2],
  },
  2: {
    id: '2',
    createdAt: '2016-12-28T23:30:13.547Z',
    name: 'Form 2',
    parentTemplate: '1',
    pdfs: [],
  },  
}

这是我的架构

import { schema } from 'normalizr'

const formTemplate = new schema.Entity('formTemplates', {}, {
  processStrategy: value => ({
      id: value.id,
      name: value.attributes.title,
      isGlobal: value.attributes.is_global,
    }),
})

const form = new schema.Entity('forms', {
  pdfs: [pdf],
}, {
  processStrategy: value => ({
    id: value.id,
    createdAt: value.attributes.created_at,
    name: value.attributes.title,
    parentTemplate: value.attributes.form_template_id,
    pdfs: [...value.relationships.documents.data],
  }),
})

const pdf = new schema.Entity('pdfs')

export default {
  data: [form],
  included: [formTemplate],
}

这是我正在规范化的API响应的一个例子

{
  "data": [
    {
      "id": "5",
      "type": "provider_forms",
      "attributes": {
        "title": "Form 1",
        "created_at": "2017-01-02T06:00:42.518Z",
        "form_template_id": 1
      },
      "relationships": {
        "form_template": {
          "data": {
            "id": "1",
            "type": "form_templates"
          }
        },
        "documents": {
          "data": [ // some pdf data here ]
        }
      }
    }
  ],
  "included": [
    {
      "id": "1",
      "type": "form_templates",
      "attributes": {
        "title": "Form Template",
        "created_at": "2016-12-29T22:24:36.201Z",
        "updated_at": "2017-01-02T06:00:20.205Z",
        "is_global": true
      },
    }
  ]
}

2 个答案:

答案 0 :(得分:0)

您将无法使用Normalizr执行此操作,因为表单模板实体没有返回表单实体的上​​下文。你的行动/减少者需要处理这个问题。

答案 1 :(得分:0)

好的,我想出了一种方法。我改变了我的formTemplate实体,以便手动映射它们,如下所示:



const formTemplate = new schema.Entity('formTemplates', {}, {
  processStrategy: (value, parent) => {
    // eslint-disable-next-line eqeqeq
    const childrenForms = parent.data.filter(form => form.attributes.form_template_id == value.id)

    return {
      id: value.id,
      name: value.attributes.title,
      isGlobal: value.attributes.is_global,
      forms: childrenForms.map(form => form.id),
    }
  },
})