Skip to content

Instantly share code, notes, and snippets.

@thetutlage
Created April 26, 2018 18:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thetutlage/d0e2c872a2a3d5df93fbc7e11ed088be to your computer and use it in GitHub Desktop.
Save thetutlage/d0e2c872a2a3d5df93fbc7e11ed088be to your computer and use it in GitHub Desktop.
Adonis JSONAPI serializer
'use strict'
const _ = use('lodash')
/**
* JSONAPI serializer for lucid models.
*
* NOTE: The implementation is not complete yet.
*
* @class JsonAPISerializer
* @constructor
*/
class JsonAPISerializer {
constructor (rows, pages, isOne = false) {
this.rows = rows
this.pages = pages
this.isOne = isOne
}
/**
* Attaches relationships to the output row
*
* @method _attachRelations
*
* @param {Model} modelInstance
* @param {Object} output
*
* @return {void}
*
* @private
*/
_attachRelations (modelInstance, output) {
_.each(modelInstance.$relations, (values, relation) => {
output[relation] = values && typeof (values.toJSON) === 'function' ? values.toJSON() : values
})
/**
* Set an array of relationships added to the JSON. This is
* required by the `jsona` library itself
*/
output.relationshipNames = _.keys(modelInstance.$relations)
}
/**
* Serializes a single model instance to a JSON API resource
*
* @method _serialize
*
* @param {Model} modelInstance
*
* @return {Object}
*
* @private
*/
_serialize (modelInstance) {
const json = _.transform(modelInstance.toObject(), (result, value, key) => {
result[_.kebabCase(key)] = value
return result
}, {})
this._attachRelations(modelInstance, json)
/**
* Setting type on the output json row. This is required
* as per JSON API specs
*/
json.type = modelInstance.constructor.resourceName || _.kebabCase(modelInstance.constructor.table)
return json
}
/**
* Add a new row to existing rows
*
* @method addRow
*
* @param {Object} row
*/
addRow (row) {
this.rows.push(row)
}
/**
* Returns the length of rows
*
* @method size
*
* @return {Number}
*/
size () {
return this.rows.length
}
/**
* Returns the first row
*
* @method first
*
* @return {Object}
*/
first () {
return this.rows[0]
}
/**
* Returns the last row
*
* @method last
*
* @return {Object}
*/
last () {
return this.rows[this.rows.length - 1]
}
/**
* Returns the serialized json
*
* @method toJSON
*
* @return {Array|Null}
*/
toJSON () {
if (this.isOne) {
return this._serialize(this.rows)
}
return this.rows.map((row) => this._serialize(row))
}
}
module.exports = JsonAPISerializer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment