Tuesday, 20 August 2019

Is there any way to normalize JSON hash in the following way using normalizr?

I need to normalize response from a server. We use normalizr to obtain a normalized redux store but for a new endpoint I need more than just an array of ids which represents a relation between different objects

I understand that I can reduce the resulting hash of widgets and change it by myself. However I'd like to describe the whole scenario using normalizr

const { normalize, schema } = require('normalizr')
data = { "dashboards": [{ "id": 1, "name": "Main", "widgets": [{ "id": 3, "kind": "stock_levels" }] }] }
const widgetSchema = new schema.Entity('widgets', {}, { idAttribute: 'id' })
dashboardSchema = new schema.Entity('dashboards', { widgets: [widgetSchema]}, { idAttribute: 'id' })
result = normalize(data.dashboards, [dashboardSchema])


Actual:

{
  "entities": {
    "widgets": {
      '3': {
        "id": 3,
        "kind": 'stock_levels'
      }
    },
    "dashboards": {
      '1': {
        "id": 1,
        "name": 'Main', "widgets": [3]
      }
    }
  },
  "result": [ 1 ]
}


Expected:

{
  "entities": {
    "widgets": {
      '3': {
        "id": 3,
        "kind": 'stock_levels'
      }
    },
    "dashboards": { 
      '1': { 
        "id": 1, 
        "name": 'Main', "widgets": {
          "stock_levels": 3 
        } 
      } 
    }
  },
  "result": [ 1 ]
}




from Is there any way to normalize JSON hash in the following way using normalizr?

No comments:

Post a Comment