apeman-app-rest
Version:
apeman app to handle restful endpoint.
75 lines (62 loc) • 1.53 kB
JavaScript
/**
* @augments Endpoint
* @class BulkRelationDestroyEndpoint
*/
const Endpoint = require('../endpoint')
const validateModelExists = require('../../validating/validate_model_exists')
const { defineRelationDestroy } = require('apemanmodel')
const co = require('co')
/** @lends BulkRelationDestroyEndpoint */
class BulkRelationDestroyEndpoint extends Endpoint {
/**
* @override
*/
getDefaultConfig () {
return {
name: 'bulkRelationDestroy'
}
}
/**
* @override
*/
handle (ctx, next) {
const s = this
let succeed = s.bindSucceed(ctx)
let fail = s.bindFail(ctx)
let { state } = ctx
let { data, id } = state
return co(function * () {
let error = s.validate(data, state)
if (error) {
return fail(error)
}
let count = yield s.bulkRelationDestroy(id, data, state)
return succeed(
{ count }
)
})
}
/**
* @override
*/
validate (data, state) {
let { model, id, instance } = state
let existsError = validateModelExists(model, id, instance)
if (existsError) {
return existsError
}
return null
}
bulkRelationDestroy (id, data, state) {
let { model, association, transaction } = state
let relationDestroy = defineRelationDestroy(model, association, transaction)
return co(function * () {
let count = 0
for (let d of data) {
count += yield relationDestroy(id, d)
}
})
}
}
module.exports = BulkRelationDestroyEndpoint