npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

node-jsonapi

v1.1.9

Published

This library helps you build and parse JSON response using JSON API format.

Downloads

28

Readme

node-jsonapi

This library helps you build and parse JSON response using JSON API format.


Installation

$ yarn add node-jsonapi

Initialization

const JSONApi = require('node-jsonapi');
const API = new JSONApi(options);

Options

key | required | type | description --------- | -------- | ------ | ------------------------------------------------------ version | no | string | JSON API version. Currently only support JSON API v1.0

Initialization without options

const JSONApi = require('node-jsonapi');
const API = new JSONApi();

Initialization with options

const JSONApi = require('node-jsonapi');
const API = new JSONApi({
  version: '1.0',
});

Methods

  • build()
  • error()
  • parse()

build()

Build valid JSON API response. Return a promise.

const JSONApi = require('node-jsonapi');
const API = new JSONApi();

// Assuming this is the data from SQL
let data = [{
  id: 1,
  title: 'FOO',
  userId: 10,
  userEmail: '[email protected]',
},
{
  id: 2,
  title: 'BAR',
  userId: 12,
  userEmail: '[email protected]',
},
{
  id: 3,
  title: 'FOOBAR',
  userId: 10,
  userEmail: '[email protected]',
}];

let options = {
  type: 'post',
  data: data,
  relationships: {
    author: {
      type: 'user',
      attributes: [ 'userId', 'userEmail' ],
      id: 'userId',
      singular: true,
    },
  },
};

API.build(options)
  .then(res.json)
  .catch((err) => {
    res.status(400);
    res.json(err);
  });

Resolved object

{
  "jsonapi": {
    "version": "1.0"
  },
  "data": [
    {
      "type": "post",
      "relationships": {
        "author": {
          "data": {
            "id": 10,
            "type": "user"
          },
          "meta": {
            "singular": true
          }
        }
      },
      "id": 1,
      "attributes": {
        "title": "FOO"
      }
    },
    {
      "type": "post",
      "relationships": {
        "author": {
          "data": {
            "id": 12,
            "type": "user"
          },
          "meta": {
            "singular": true
          }
        }
      },
      "id": 2,
      "attributes": {
        "title": "BAR"
      }
    },
    {
      "type": "post",
      "relationships": {
        "author": {
          "data": {
            "id": 10,
            "type": "user"
          },
          "meta": {
            "singular": true
          }
        }
      },
      "id": 3,
      "attributes": {
        "title": "FOOBAR"
      }
    }
  ],
  "included": [
    {
      "type": "user",
      "id": 10,
      "attributes": {
        "userEmail": "[email protected]"
      }
    },
    {
      "type": "user",
      "id": 12,
      "attributes": {
        "userEmail": "[email protected]"
      }
    }
  ]
}

Options

key | required | type | description --------------- | -------- | ------- | ------------------------------------------------------------- type | yes | string | Response data type id | no | string | Key for data id when id key doesn't exist data | yes | object | Response data. See data structure below relationships | no | object | Data relationship scheme. See relationships structure below singular | no | boolean | Whether it's a single or multiple data

Data structure

key | required | type | description ---------- | -------- | ---------------- | ------------- id | yes | string or number | Data id any keys | no | any | Any data keys

Example of single data structure

let options = {
  //...
  data: {
    id: 1,
    title: 'foo',
  },
  //...
};

Example of multiple data structure

let options = {
  //...
  data = [
    { id: 1, title: 'foo' },
    { id: 2, title: 'bar' },
  ],
  //...
};

Relationships structure (optional)

This is the relationship scheme

key | required | type | description ------------- | -------- | ------- | ----------------------------------------- name | yes | string | Relationship name /type | yes | string | Relationship type /id | yes | string | Relationship id /attributes | yes | array | Relationship attributes /singular | no | boolean | Whether the relationship data is singular

Example

let options = {
  //...
  relationships: {
    author: {
      type: 'user',
      attributes: [ 'userId', 'userEmail' ],
      id: 'userId',
      singular: true,
    },
  },
  //...
};

error()

Build valid JSON API error response. Return a promise.

const JSONApi = require('node-jsonapi');
const API = new JSONApi();

let errors = [{
  status: 400,
  code: 'ERR_API_SET_PROFILE',
  title: 'Failed to set author profile',
  detail: 'Missing author name',
  source: 'profiles.create'
}];

API.error(errors)
  .then(res.json)
  .catch((err) => {
    res.status(400);
    res.json(err);
  });

Resolved object

{
  "jsonapi": {
    "version": "1.0"
  },
  "errors": [
    {
      "status": 400,
      "code": "ERR_API_SET_PROFILE",
      "title": "Failed to set author profile",
      "detail": "Missing author name",
      "source": "profiles.create"
    }
  ]
}

Errors structure

Errors is an Array of error.

Error

key | required | type | description -------- | -------- | ---------------- | ------------ status | yes | number | HTTP status code | yes | string or number | Error code title | no | string | Error title detail | no | string | Error detail source | no | string | Error source


parse()

Parse valid JSON API response to flat plain object. Return a promise.

const JSONApi = require('node-jsonapi');
const API = new JSONApi();

const jsonData = {
  "jsonapi": {
    "version": "1.0"
  },
  "data": [
    {
      "type": "post",
      "relationships": {
        "author": {
          "data": {
            "id": 10,
            "type": "user"
          },
          "meta": {
            "singular": true
          }
        }
      },
      "id": 1,
      "attributes": {
        "title": "FOO"
      }
    },
    {
      "type": "post",
      "relationships": {
        "author": {
          "data": {
            "id": 12,
            "type": "user"
          },
          "meta": {
            "singular": true
          }
        }
      },
      "id": 2,
      "attributes": {
        "title": "BAR"
      }
    },
    {
      "type": "post",
      "relationships": {
        "author": {
          "data": {
            "id": 10,
            "type": "user"
          },
          "meta": {
            "singular": true
          }
        }
      },
      "id": 3,
      "attributes": {
        "title": "FOOBAR"
      }
    }
  ],
  "included": [
    {
      "type": "user",
      "id": 10,
      "attributes": {
        "userEmail": "[email protected]"
      }
    },
    {
      "type": "user",
      "id": 12,
      "attributes": {
        "userEmail": "[email protected]"
      }
    }
  ]
};

API.parse(jsonData)
  .then(res.json)
  .catch((err) => {
    res.status(400);
    res.json(err);
  });

Resolved object

{
  "data": [
    {
      "author": {
        "userId": 10,
        "userEmail": "[email protected]"
      },
      "postId": 1,
      "title": "FOO"
    },
    {
      "author": {
        "userId": 12,
        "userEmail": "[email protected]"
      },
      "postId": 2,
      "title": "BAR"
    },
    {
      "author": {
        "userId": 10,
        "userEmail": "[email protected]"
      },
      "postId": 3,
      "title": "FOOBAR"
    }
  ]
}