json-api-ify
a node.js
library for serializing your data to JSON API v1.0 compliant documents, inspired by jsonapi-serializer. this library makes no assumptions regarding your choice of ORM/ODM, or the structure of your data. simply define your types and how their related and let this library do the heavy lifting.
Installing
npm install --save json-api-ify
Getting Started
Create a new reusable serializer.
var Serializer = ; let serializer = baseUrl: 'https://www.example.com/api' topLevelMeta: 'api-version': 'v1.0.0' ;
Define a type. (read more about options below)
serializer
Get a hold of some data that needs to be serialized.
let data = first: 'Kendrick' last: 'Lamar' email: 'klamar@example.com' password: 'elkjqe0920oqhvrophepohiwveproihgqp398yr9pq8gehpqe9rf9q8er' phone: home: '+18001234567' mobile: '+180045678910' address: addressLine1: '406 Madison Court' zipCode: '49426' country: 'USA' first: 'Kanye' last: 'West' email: 'kwest@example.com' password: 'asdlkj2430r3r0ghubwf9u3rbg9u3rbgi2q3oubgoubeqfnpviquberpibq' phone: home: '+18002345678' mobile: '+18007890123' address: addressLine1: '361 Shady Lane' zipCode: '23185' country: 'USA' ;
Serialize it
serializer;
Or, use it in a route
{ async;}
Response body:
Schemas
A type can have multiple serialization schemas, which you can create by calling define
with a schema name. Any schema options provided will augment the default schema.
serializer;
serializer;
Relationships
Relationships are easy as well. First, include a relationship map in your type/schema options.
serializer;
Lastly, define the related type.
serializer;
Deserialize
extract the data from a payload in a slightly more usable fashion
let payload = data: type: 'user' attributes: first: 'a$ap' last: 'ferg' email: 'aferg@example.com' phone: home: '1-111-111-1111' relationships: groups: data: type: 'group' id: '56cd74546033f8d420bc1c11' type: 'group' id: '56cd74546033f8d420bc1c12' ;serializer;
here, data would look like:
API
Constructor Summary
Serializer([options])
constructs a new serializer instance
Arguments
Param | Type | Description |
---|---|---|
[options] |
{Object} |
global options. see serialize() options for more detail |
Method Summary
define(type, [schema], options, callback)
defines a type serialization schema
Arguments
Param | Type | Description |
---|---|---|
type |
{String} |
the resource type |
[schema] |
{String} |
the serialization schema to use. defaults to default |
options |
{Object} |
schema options |
callback(err) |
{Function} |
a function that receives any definition error. |
deserialize(payload, callback)
deserializes the data attribute of the payload
Arguments
Param | Type | Description |
---|---|---|
payload |
{Object} |
a valid JSON API payload |
callback(err, data) |
{Function} |
a function that receives any deserialization error and the extracted data. |
serialize(type, [schema], data, [options], callback)
serializes data
into a JSON API v1.0 compliant document
Arguments
Param | Type | Description |
---|---|---|
type |
{String} |
the resource type |
[schema] |
{String} |
the serialization schema to use. defaults to default |
data |
{*} |
the data to serialize |
[options] |
{Object} |
single use options. these options will be merged with the global options, default schema options, and any applicable non-default schema options |
callback(err, payload) |
{Function} |
a function that receives any serialization error and JSON API document. |
Options
// an array of string paths to omit from the resource, this option // includes relationships that you may wish to omit blacklist: // the path to the primary key on the resource id: 'id' // a map of resource links links: // asynchronous { // each key can be a value to set, or asynchronous function that // receives the processed resource, serialization options, and // a callback that should pass any error and the link value ; } // synchronous { return optionsbaseUrl + '/api/users/' + resourceid; } // a map of meta members meta: // asynchronous { // each key can be a value to set, or asynchronous function that // receives the processed resource, serialization options, and // a callback that should pass any error and the meta value ; } // synchronous { return meta; } // preprocess your resources // all resources must be objects, otherwise they're assumed to be // unpopulated ids. NOTE!! If you're working with mongoose models, // unpopulated ids can be objects, so you will need to convert them // to strings { if typeof resourcetoJSON === 'function' resource = resource; else if resource instanceof mongooseTypesObjectId resource = resource; return resource; } // relationship configuration relationships: // each key represents a resource path that points to a // nested resource or collection of nested resources 'groups': // the type of resource type: 'groups' // whether or not to include the nested resource(s) include: true // optionally specify a non-default schema to use schema: 'my-schema' // a map of links to define on the relationship object links: { } { } // a map of top-level links topLevelLinks: { } // a map of top-level meta members meta: { } // an array of string paths to pick from the resource. this option // overrides any specified blacklist and also includes relationships whitelist:
serializeError(error, [meta], [defaultStatusCode]) => {object} document
serializes any error
into a JSON API v1.0 compliant error document. error can be anything, this method will attempt to intelligently construct a valid JSON API error object. the return document will contain a top level meta
member with a status
attribute that represents the status code with the greatest frequency.
Arguments
Param | Type | Description |
---|---|---|
error |
{*} |
the error data to serialize |
[meta] |
{Object} |
any top level meta information |
[defaultStatusCode] |
{Number|String} |
a default status code to apply to any error object(s) without a specified status |
Example
{ async;}
Events
The serializer
inherits from node's EventEmitter
. Below is a summary of the events exposed by this library.
error
The global error event.
Arguments
Param | Type | Description |
---|---|---|
error |
{Object} |
the error object |
Example
serializer;
To Do
- implement
jsonapi
top-level member - implement
deserialize
method - implement support for unpopulated relationships (an id, or array of ids)
- implement templates
- ADD MORE TESTS!
Testing
run tests
npm test
Contributing
- Fork it
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create new Pull Request
License
Copyright (c) 2016 Chris Ludden.
Licensed under the MIT license.