Code Monkey home page Code Monkey logo

json-api-helper's Introduction

A simple solution to work with JSON API data in JS.

Installation

yarn add @leobagua/json-api-helper

or

npm install @leobagua/json-api-helper

Usage

import { Deserializer } from '@leobagua/json-api-helper'

Deserializer.deserialize(response)

Examples:

Collection

A JSON Api Response

 {
   "meta": {
     "page": 1,
     "resources_per_page": 5,
     "total_resources": 6
   },
   "data": [
     {
       "type": "authors",
       "id": "1",
       "attributes": {
         "name": "Leonardo da Rosa",
         "birthplace": "Brazil"
       },
       "relationships": {
         "photos": {
           "data": [
             {
               "type": "photos",
               "id": "7"
             },
             {
               "type": "photos",
               "id": "8"
             }
           ]
         },
         "books": {
           "data": [
             {
               "type": "books",
               "id": "1"
             },
             {
               "type": "books",
               "id": "33"
             }
           ]
         }
       },
       "links": {
         "self": "/authors/7"
       }
     }
   ],
   "included": [
     {
       "type": "photos",
       "id": "7",
       "attributes": {
         "title": "Photo 365",
         "uri": "https:\/\/picsum.photos\/id\/378\/400\/300.jpg"
       }
     },
     {
       "type": "photos",
       "id": "8",
       "attributes": {
         "title": "Photo 786",
         "uri": "https:\/\/picsum.photos\/id\/529\/400\/300.jpg"
       }
     },
     {
       "type": "books",
       "id": "1",
       "attributes": {
         "title": "O'Kon, Gorczany and Langworth",
         "date_published": "1987-01-25",
         "isbn": 4294967295
       }
     },
     {
       "type": "books",
       "id": "33",
       "attributes": {
         "title": "Simonis, Simonis and Mills",
         "date_published": "1982-11-30",
         "isbn": 1304049345
       }
     }
   ]
 }

Will be parsed as:

[
  {
    "id": 1,
    "name": "Leonardo da Rosa",
    "birthplace": "Brazil",
    "author_links": {
      "self": "/authors/7"
    },
    "author_meta": {},
    "photos": [
      {
        "id": 7,
        "title": "Photo 365",
        "uri": "https://picsum.photos/id/378/400/300.jpg",
        "photo_links": {},
        "photo_meta": {}
      },
      {
        "id": 8,
        "title": "Photo 786",
        "uri": "https://picsum.photos/id/529/400/300.jpg",
        "photo_links": {},
        "photo_meta": {}
      }
    ],
    "books": [
      {
        "id": 1,
        "title": "O'Kon, Gorczany and Langworth",
        "date_published": "1987-01-25",
        "isbn": 4294967295,
        "book_links": {},
        "book_meta": {}
      },
      {
        "id": 33,
        "title": "Simonis, Simonis and Mills",
        "date_published": "1982-11-30",
        "isbn": 1304049345,
        "book_links": {},
        "book_meta": {}
      }
    ]
  }
]

Object

A JSON Api Response

{
  "data": {
    "id": 1,
    "type": "company",
    "attributes": {
      "name": "My Company",
      "number_of_employers": 20
    },
    "relationships": {
      "config": {
        "data": {
          "id": 1,
          "type": "config"
        }
      },
      "addresses": {
        "data": [
          {
            "id": 1,
            "type": "address"
          }
        ]
      },
      "stages": {
        "data": [
          {
            "id": 1,
            "type": "stage"
          },
          {
            "id": 2,
            "type": "stage"
          },
          {
            "id": 3,
            "type": "stage"
          }
        ]
      }
    }
  },
  "included": [
    {
      "id": 1,
      "type": "address",
      "attributes": {
        "street": "Company street",
        "country": "Brazil"
      }
    },
    {
      "id": 1,
      "type": "config",
      "attributes": {
        "logo": "/assets/fallback/my-logo.png"
      },
      "relationships": {
        "benefits": {
          "data": [
            {
              "id": 1,
              "type": "benefit"
            },
            {
              "id": 2,
              "type": "benefit"
            }
          ]
        },
        "images": {
          "data": []
        }
      }
    },
    {
      "id": 1,
      "type": "benefit",
      "attributes": {
        "value_type": "Percentage",
        "periodicity": "Monthly",
        "extensible": true,
        "value": 80.00
      }
    },
    {
      "id": 2,
      "type": "benefit",
      "attributes": {
        "value_type": "Value",
        "periodicity": "Monthly",
        "extensible": false,
        "value": 299.90
      }
    }
  ]
}

Will be parsed as:

{
  id: 1,
  name: 'My Company',
  number_of_employers: 20,
  company_links: {},
  company_meta: {},
  config: {
    id: 1,
    logo: '/assets/fallback/my-logo.png',
    config_links: {},
    config_meta: {}
  },
  addresses: [
    {
      id: 1,
      street: 'Company street',
      country: 'Brazil',
      address_links: {},
      address_meta: {}
    }
  ]
}

Multi-case types

To prevent some tedious work with use of different types of the naming convention of the deserialized data, a layer of multi-case type was added to help to get and set each parsed attribute, accordantly with the proffered case-type. So, you can access each object attribute with your preferred case-type:

company = Deserializer.deserialize(response)

// Getter
company.company_name // 'My company'
company.companyName // 'My company'
company.CompanyName // 'My company'
company['company-name'] // 'My company'

// Setter
company.company_name = 'My company in snake_case'
company.companyName = 'My company in camelCase'
company.CompanyName = 'My company in PascalCase'
company['kebab-case'] = 'My company in kebab-case'

json-api-helper's People

Contributors

leobagua avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Forkers

rsales swipswaps

json-api-helper's Issues

Build the Model that will be hydrated with the deserialized data

Build a clean, performatic and redable code to Model of the JSON API data, that will be the final, normalized and deserialized response from the backend.

The model at start, will need to be able to do:

  • Handle multiple formats of the attributes names. The attribute needs to handle the get/set as camelCase, snake_case ou PascalCase format.
    Eg: company = new Model({my_name: 'My Company'})
    company.my_name -> "My Company"
    company.myName -> "My Company"
    company.MyName -> "My Company"

Empty relations are causing no object error

static parseRelationships(relationships = {}) {

hasMany[relationship] = data.map((object) => this.normalizeObject(object))

hasOne[relationship] = this.normalizeObject(data)

This happens when you have an empty relationship.

What is needed to do:

  • Fix the code to handle empty relationships.
  • Create a new test case to cover this issue.

Build the data deserialization based on JSON API v 1.0

Build a clean, performatic and redable code to deserialization of the JSON API data, based on the v1.0 specification.

JSON API v1.0

The deserelization at start, will need to be able to do:

  • Merge the attributes in the root level of the object. Eg: {id: 1, attributes: {name: 'Name'}} -> {id: 1, name: 'Name'}

Relationships on included resources are not been parsed correctly

The associations on included resources are not been parsed as expected:

Response:

{
  data: {
    id: 20,
    type: "Company",
    attributes: {
      name: "My Company"
    }
    relationships: [
      config: {
        id: 1,
        type: "Config"
      }
    ]
   },
  included: [
    {
      id: 1,
      type: 'config',
      attributes: {
        color: 'red'
      },
      relationships: [
        {
          id: 150,
          type: 'address'
        }
      ]
    },
   {
     id: 150,
     type: 'address',
     attributes: {
       street: 'My Street'
     },
   }
  ]
}

Expected:

{
  id: 20,
  name: "My Company",
  config: {
    id: 1,
    color: "red",
    address: {
      id: 150,
      street: "My Street'
    }
  }
}

Actual:

{
  id: 20,
  name: "My Company",
  config: {
    id: 1,
    color: "red"
  }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.