JSON API Serializer
A Node.js framework agnostic library for serializing your data to JSON API (1.0 compliant).
Installation
$ npm install jsonapi-serializer
Documentation
JSONAPISerializer(type, data, opts) serializes the data (can be an object or an array) following the rules defined in opts.
- type: The resource type.
- data: An object to serialize.
- opts
- 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.
- 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
- 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. Option pluralizeType ignored if set.
- meta: An object to include non-standard meta-information.
- 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).
Examples ### Simple usage
// Sample data objectvar data = id: 1 firstName: 'Sandro' lastName: 'Munda' id: 2 firstName: 'John' lastName: 'Doe' ;
var JSONAPISerializer = Serializer; var users ='users' data topLevelLinks: self: 'http://localhost:3000/api/users' dataLinks: { return 'http://localhost:3000/api/users/' + userid } attributes: 'firstName' 'lastName'; // `users` here are JSON API compliant.
The result will be something like:
"links": "self": "http://localhost:3000/api/users" "data": "type": "users" "id": "1" "attributes": "first-name": "Sandro" "last-name": "Munda" "links": "http://localhost:3000/api/users/1" "type": "users" "id": "2" "attributes": "first-name": "John" "last-name": "Doe" "links": "http://localhost:3000/api/users/2"
var users = new JSONAPISerializer('users', data, { topLevelLinks: { self: 'http://localhost:3000/api/users' }, attributes: ['firstName', 'lastName', 'address'], address: { attributes: ['addressLine1', 'zipCode', 'city'] } });
// users
here are JSON API compliant.
The result will be something like:
```javascript
{
"links": {
"self": "http://localhost:3000/api/users"
},
"data": [{
"type": "users",
"id": "1",
"attributes": {
"first-name": "Sandro",
"last-name": "Munda",
"address": {
"address-line1": "630 Central Avenue",
"zip-code": 24012,
"city": "Roanoke"
}
}
}, {
"type": "users",
"id": "2",
"attributes": {
"first-name": "John",
"last-name": "Doe",
"address": {
"address-line1": "400 State Street",
"zip-code": 33702,
"city": "Saint Petersburg"
}
}
}]
}
### Compound document
var JSONAPISerializer = ; var users = 'users' data topLevelLinks: self: 'http://localhost:3000/api/users' attributes: 'firstName' 'lastName' 'books' books: ref: '_id' attributes: 'title' 'isbn' relationshipLinks: "self": "http://example.com/relationships/books" "related": "http://example.com/books" relationshipMeta: { return userbookslength; } includedLinks: { return 'http://example.com/books/' + bookid; } ; // `users` here are JSON API compliant.
The result will be something like:
"links": "self": "http://localhost:3000/api/users" "data": "type": "users" "id": "1" "attributes": "first-name": "Sandro" "last-name": "Munda" "relationships": "books": "data": "type": "books" "id": "1" "type": "books" "id": "2" "links": "self": "http://example.com/relationships/books" "related": "http://example.com/books" "meta": "count": 2 "type": "users" "id": "2" "attributes": "first-name": "John" "last-name": "Doe" "relationships": "books": "data": "type": "books" "id": "3" "links": "self": "http://example.com/relationships/books" "related": "http://example.com/books" "meta": "count": 1 "included": "type": "books" "id": "1" "attributes": "title": "La Vida Estilista" "isbn": "9992266589" "links": "self": "http://example.com/books/1" "type": "books" "id": "2" "attributes": "title": "La Maria Cebra" "isbn": "9992264446" "links": "self": "http://example.com/books/2" "type": "books" "id": "3" "attributes": "title": "El Salero Cangrejo" "isbn": "9992209739" "links": "self": "http://example.com/books/3"
JSONAPIDeSerializer(collectionName, payload) deserializes a JSON API payload
(e.g req.body or res.body) into collectionName it can be either {}
or
an Object "Class".
- collectionName: {} or Object ("Class")
- payload: JSON API compliant payload
JSON API Payload
var body = "data": "id": "1453732635522" "attributes": "order-type": "subscription" "production-state": "0" "payment-state": "0" "shipment-state": "0" "created-at": null "ship-date": null "season": "WN16" "box-status": "items choosen" "has-add-ons": false "relationships": "plan": "data": "type": "plans" "id": "2-shirt" "details": "data": "type": "order-details" "id": "1453732637371" "customer": "data": "type": "customers" "id": "1453732635522" "type": "orders"
var JSONAPIDeSerializer = DeSerializer;var serialized = {} body;
Result
"orderType": "subscription" "productionState": "0" "paymentState": "0" "shipmentState": "0" "createdAt": null "shipDate": null "season": "WN16" "boxStatus": "items choosen" "hasAddOns": false "plan": "id": "2-shirt" "details": "id": "1453732637371" "customer": "id": "1453732635522" "id": "1453732635522"
Example with Express Server and Mongoose
var express = ;var bodyParser = ;var JSONAPIDeSerializer = DeSerializer;var _ = ; // parse application/jsonapp; // parse application/vnd.api+json as jsonapp; /** * JSON API Content-Type HEADER */app; var orders = ; // JSON API deserializer as express middlewareapp; // Resourcesapp;
Normalize JSON API relationships into Mongoose relationships
var _ = ; // relationships comes in { plan: { id: '1-shirt' } }// but because we are using Mongoose, id doesn't allow us to use plain JS objects// so we need to extract ids { var normalizedData = {}; relationships = relationships || {}; Object; return normalizedData;} moduleexportsnormalize = normalize;
Order Schema
var mongoose = ;var Schema = mongooseSchema; var OrderSchema = customer: type: SchemaTypesObjectId ref: 'Customer' address: type: SchemaTypesObjectId ref: 'Address' season: type: String details: type: SchemaTypesObjectId ref: 'OrderDetail' createdAt: type: Date default: Date updatedAt: type: Date default: Date ;
Order's Route
var Express = ;var Order = Order;var Serializer = ;var OrdersSerializer = ; var app = ; /** * POST */; moduleexports = app;