How to add array of ids to entity that doesn't have them

448 views Asked by At

I have my schema set up almost exactly how I want it in redux state, except I want to add an array of form ids to the formTemplate object. It would look like this:

// 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: [],
  },  
}

Here is my schema

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],
}

This is an example of the API response that I'm normalizing

{
  "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

There are 2 answers

0
Colby CheeZe On

Okay I figured out a way to do this. I changed my formTemplate entity to map them in manually like so:

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),
    }
  },
})

0
Paul Armstrong On

You won't be able to do this with Normalizr because the form template entity has no context back to the forms entities. Your actions/reducer need to handle this.