JSON API Standard v1 Normalization

I was looking for normalizr to align JSON API data formatted in standard JSON API format . Can someone point me to some examples of this? I specifically focus on how to handle the normalizr schema for resource object relationships (as defined by the JSON API standard). In the JSON API standard, there is a “relationship” property defined in a resource object, and then properties for each group of related objects. Here is an example of one product category in JSON API format with two related products:

{
  "jsonapi": {
    "version": "1.0"
  },
  "meta": {
    "time": "0.006"
  },
  "data": [
    {
      "type": "category",
      "id": "6",
      "attributes": {
        "name": "Odwalla"
      },
      "meta": {
        "product_count": "0"
      },
      "relationships": {
        "product": {
          "data": [
            {
              "type": "product",
              "id": "4785"
            },
            {
              "type": "product",
              "id": "4786"
            }
          ]
        }
      }
    }
  ],
  "included": [
    {
      "type": "product",
      "id": "4786",
      "attributes": {
        "name": "Strawberry & Banana Odwalla",
        "description": null,
        "price": "3.19",
        "upc": ""
      }
    },
    {
      "type": "product",
      "id": "4785",
      "attributes": {
        "name": "Blueberry Odwalla",
        "description": null,
        "price": "3.19",
        "upc": ""
      }
    }
  ]
}

, , data.relationships.product.data, . , ; Flux/Redux?

+4
1

json: api . , included - . "" . normalizr , -, , normalizr, . - , json: api - , . , "" normalizr...

import { reduce, append } from 'ramda'

export default function normalize({data, included}) {
  let bag = {}
  const result = visit(data, bag)
  visit(included, bag)

  return {
    entities: bag,
    result
  }
}

function visitIterable(obj, bag) {
  return reduce((acc, item) => {
    const entityId = visitEntity(item, bag)
    return append(entityId, acc)
  }, [], obj)
}

function visitEntity(obj, bag) {
  const entityKey = obj.type
  const entityId = obj.id

  if (!bag.hasOwnProperty(entityKey)) {
    bag[entityKey] = {}
  }

  bag[entityKey][entityId] = obj
  return entityId
}

function visit(obj, bag) {
  if (Array.isArray(obj)) {
    return {
      list: visitIterable(obj, bag)
    }
  } else if (typeof obj === 'object') {
    return {
      item: visitEntity(obj, bag)
    }
  }
}
+9

Source: https://habr.com/ru/post/1614376/


All Articles