apeman-app-rest
Version:
apeman app to handle restful endpoint.
80 lines (66 loc) • 1.64 kB
JavaScript
/**
* Endpoint for relation list
* @augments Endpoint
* @class RelationListEndpoint
*/
const Endpoint = require('./endpoint')
const { toData, defineRelatedGet } = require('apemanmodel')
const validateModelExists = require('../validating/validate_model_exists')
const co = require('co')
/** @lends RelationListEndpoint */
class RelationListEndpoint extends Endpoint {
/**
* @override
*/
getDefaultConfig () {
return {
name: 'relationList'
}
}
/**
* @override
*/
handle (ctx, next) {
const s = this
let succeed = s.bindSucceed(ctx)
let fail = s.bindFail(ctx)
let { state } = ctx
let { association, instance } = state
return co(function * () {
let error = s.validate(null, state)
if (error) {
return fail(error)
}
let relation = yield s.relatedList(instance, state)
return succeed(
{},
toData.withoutAttributes(association.target, relation, {}),
{
self: '.',
related: `../../${association.as}`
}
)
})
}
/**
* @override
*/
validate (data, state) {
let { model, id, instance } = state
let existsError = validateModelExists(model, id, instance)
if (existsError) {
return existsError
}
return null
}
relatedList (instance, state) {
let { model, association, transaction } = state
let relatedGet = defineRelatedGet(model, association, transaction)
return co(function * () {
return yield relatedGet(instance)
})
}
}
Object.assign(RelationListEndpoint, {})
module.exports = RelationListEndpoint