Git Product home page Git Product logo

jsonapi-serializer's Introduction

JSON API Serializer

Build Status

A Node.js framework agnostic library for serializing your data to JSON API (1.0 compliant).

Installation

$ npm install jsonapi-serializer

Documentation

Serialization

var JSONAPISerializer = require('jsonapi-serializer').Serializer;
new JSONAPISerializer(type, opts).serialize(data);

The function JSONAPISerializer takes two arguments:

  • type: The resource type.
  • opts: The serialization options.

Calling the serialize method on the returned object will serialize your data (object or array) to a compliant JSONAPI document.

Available serialization option (opts argument)

  • attributes: An array of attributes to show. You can define an attribute as an option if you want to define some relationships (included or not).
    • ref: If present, it's considered as a relationships.
    • included: Consider the relationships as compound document. Default: true.
    • id: Configurable identifier field for the resource. Default: id.
    • attributes: An array of attributes to show.
    • topLevelLinks: An object that describes the top-level links. Values can be string or a function (see examples below)
    • dataLinks: An object that describes the links inside data. Values can be string or a function (see examples below)
    • relationshipLinks: An object that describes the links inside relationships. Values can be string or a function (see examples below)
    • relationshipMeta: An object that describes the meta inside relationships. Values can be string or a function (see examples below)
    • ignoreRelationshipData: Do not include the data key inside the relationship. Default: false.
    • keyForAttribute: A function or string to customize attributes. Functions are passed the attribute as a single argument and expect a string to be returned. Strings are aliases for inbuilt functions for common case conversions. Options include: dash-case (default), lisp-case, spinal-case, kebab-case, underscore_case, snake_case, camelCase, CamelCase.
    • nullIfMissing: Set the attribute to null if missing from your data input. Default: false.
    • pluralizeType: A boolean to indicate if the type must be pluralized or not. Default: true.
    • typeForAttribute: A function that maps the attribute (passed as an argument) to the type you want to override. If it returns undefined, ignores the flag for that attribute. Option pluralizeType ignored if set.
    • meta: An object to include non-standard meta-information.

Examples

Simple usage:

var data = [
  { id: 1, firstName: 'Sandro', lastName: 'Munda' },
  { id: 2, firstName: 'John', lastName: 'Doe' }
];
var JSONAPISerializer = require('jsonapi-serializer').Serializer;

var UserSerializer = new JSONAPISerializer('users', {
  attributes: ['firstName', 'lastName']
});

var users = UserSerializer.serialize(data);

// `users` here are JSON API compliant.

The result will be something like:

{
  "data": [{
    "type": "users",
    "id": "1",
    "attributes": {
      "first-name": "Sandro",
      "last-name": "Munda"
    }
  }, {
    "type": "users",
    "id": "2",
    "attributes": {
      "first-name": "John",
      "last-name": "Doe"
    }
  }]
}

Deserialization

var JSONAPIDeserializer = require('jsonapi-serializer').Deserializer;
new JSONAPIDeserializer(opts).deserialize(data);

The function JSONAPIDeserializer takes one argument:

  • opts: The deserializer options.

Calling the deserialize method on the returned object will deserialize your data (JSONAPI document) to a plain javascript object.

Available deserialization option (opts argument)

  • keyForAttribute: A function or string to customize attributes. Functions are passed the attribute as a single argument and expect a string to be returned. Strings are aliases for inbuilt functions for common case conversions. Options include: dash-case (default), lisp-case, spinal-case, kebab-case, underscore_case, snake_case, camelCase, CamelCase.
  • AN_ATTRIBUTE_TYPE: this option name corresponds to the type of a relationship from your JSONAPI document.
    • valueForRelationship: A function that returns whatever you want for a relationship (see examples below)

Examples

Simple usage:

{
  data: [{
    type: 'users',
    id: '1',
    attributes: {
      'first-name': Sandro,
      'last-name': Munda
    }
  }, {
    type: 'users',
    id: '2',
    attributes: {
      'first-name': 'John',
      'last-name': 'Doe'
    }
  }]
}
var JSONAPIDeserializer = require('jsonapi-serializer').Deserializer;

new JSONAPIDeserializer().deserialize(jsonapi, function (err, users) {
  // `users` is...
});
[
  { id: 1, firstName: 'Sandro', lastName: 'Munda' },
  { id: 2, firstName: 'John', lastName: 'Doe' }
];

Relationship:

{
  data: [{
    type: 'users',
    id: '54735750e16638ba1eee59cb',
    attributes: {
      'first-name': 'Sandro',
      'last-name': 'Munda'
    },
    relationships: {
      address: {
        data: { type: 'addresses', id: '54735722e16620ba1eee36af' }
      }
    }
  }, {
    type: 'users',
    id: '5490143e69e49d0c8f9fc6bc',
    attributes: {
      'first-name': 'Lawrence',
      'last-name': 'Bennett'
    },
    relationships: {
      address: {
        data: { type: 'addresses', id: '54735697e16624ba1eee36bf' }
      }
    }
  }]
}
var JSONAPIDeserializer = require('jsonapi-serializer').Deserializer;

new JSONAPIDeserializer({
  addresses: {
    valueForRelationship: function (relationship) {
      return {
        id: relationship.id,
        'address-line1': '406 Madison Court',
        'zip-code': '49426',
        country: 'USA'
      };
    }
  }
}).deserialize(jsonapi, function (err, users) {
  // `users` is...
});
[{
  id: '54735750e16638ba1eee59cb',
  'first-name': 'Sandro',
  'last-name': 'Munda',
  address: {
    id: '54735722e16620ba1eee36af',
    'address-line1': '406 Madison Court',
    'zip-code': '49426',
    country: 'USA'
  }
}, {
  id: '5490143e69e49d0c8f9fc6bc',
  'first-name': 'Lawrence',
  'last-name': 'Bennett',
  address: {
    id: '54735697e16624ba1eee36bf',
    'address-line1': '406 Madison Court',
    'zip-code': '49426',
    country: 'USA'
  }
}]

License

MIT

jsonapi-serializer's People

Contributors

alexsotocx avatar awochna avatar craigcartmell avatar ianvs avatar jamesdixon avatar javiacei avatar jelhan avatar kiwiupover avatar kpollich avatar lostintime avatar m-bodmer avatar nvh avatar sarus avatar seyz avatar testica avatar tonylukasavage avatar winglian avatar

Watchers

 avatar

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.