apeman-app-rest
Version:
apeman app to handle restful endpoint.
102 lines (88 loc) • 2.02 kB
JavaScript
/**
* Abstract endpoint
* @class Endpoint
*/
const defaults = require('defaults')
/** @lends Endpoint */
class Endpoint {
constructor (config) {
const s = this
defaults(config, s.getDefaultConfig())
Object.assign(s, config, { config: config })
}
getDefaultConfig () {
return {
name: null,
model: null,
singleton: false
}
}
/**
* Handle koa context
* @abstract
* @param {Object} ctx - Koa context
* @param {function} next - Call next
* @returns {Promise}
*/
handle (ctx, next) {
throw new Error('Not implemented!')
}
validate (data, state) {
throw new Error('Not implemented!')
}
// --------------------
// Payload builders
// --------------------
/**
* Build success payload.
* @param {Object} meta - JSON-API meta object
* @param {Object} data - JSON-API data object
* @param {Object} links - JSON-API link object
* @param {Object} included - JSON-API included object
* @returns {Object}
*/
success (meta, data, links, included) {
const s = this
let { name } = s
return {
meta: Object.assign({}, { action: name }, meta),
data, links, included
}
}
/**
* Build failure payload.
* @param {Object[]} errors - JSON-API error objects
* @returns {Object}
*/
failure (errors) {
const s = this
let { name } = s
return {
meta: { action: name },
errors: [].concat(errors)
}
}
// --------------------
// Method binders
// --------------------
/**
* Bind success handling with context
* @param {Object} ctx - Koa context
* @returns {function()}
*/
bindSucceed (ctx) {
const s = this
return (...args) => ctx.jsonapi(s.success(...args))
}
/**
* Bind failure handling with context
* @param {Object} ctx - Koa context
* @returns {function()}
*/
bindFail (ctx) {
const s = this
return (...args) => ctx.jsonapi(s.failure(...args))
}
}
module.exports = Endpoint