@apicase/jsonapi

0.1.1 • Public • Published

Apicase JSON API

Apicase plugin that helps you work with JSON API (based on json-api-normalize)

Read JSON API specification

click here

Installation

npm install @apicase/jsonapi
import fetch from "@apicase/adapter-fetch"
import { ApiService } from "@apicase/core"
import { jsonApiPlugin } from "@apicase/jsonapi"

const Root = new ApiService(fetch, {
  url: "/api"
}).use(jsonApiPlugin) // <- Add this line

Usage

Imagine that we have API route with the following result.body:

{
  "data": [
    {
      "id": "1",
      "type": "post",
      "attributes": {
        "title": "Hello world",
        "text": "Lorem Ipsum Dolor ..."
      },
      "relationships": {
        "author": {
          "data": {
            "id": "1",
            "type": "user"
          }
        }
      }
    }
  ],
  "included": [
    {
      "id": "1",
      "type": "user",
      "attributes": {
        "name": "Anton",
        "surname": "Kosykh"
      }
    }
  ]
}

We'll create a service with meta.normalize options:

const GetPosts = Root.extend({
  meta: {
    normalize: ["id", "title", "text", "author.id", "author.name"]
  }
})

GetPosts
  .doRequest()
  .then(({ result }) => {
    console.log(result.body)
  })

It will convert result.body to:

[
  {
    "id": "1",
    "title": "Hello world",
    "text": "Lorem Ipsum Dolor ...",
    "author": {
      "id": "1",
      "name": "Anton"
    }
  }
]

If you need links or another options from original body, it's stored in result.rawBody:

console.log(result.rawBody.included)
/*
  [{
    "id": "1",
    "type": "user",
    "attributes": {
      "name": "Anton",
      "surname": "Kosykh"
    }
  }]
*/

License

MIT

Readme

Keywords

none

Package Sidebar

Install

npm i @apicase/jsonapi

Weekly Downloads

1

Version

0.1.1

License

MIT

Unpacked Size

76.5 kB

Total Files

5

Last publish

Collaborators

  • kelin2025