apeman-app-rest
Version:
apeman app to handle restful endpoint.
84 lines (71 loc) • 1.74 kB
JavaScript
/**
* Endpoint for bulk destroy
* @augments Endpoint
* @class BulkDestroyEndpoint
*/
const Endpoint = require('../endpoint')
const { toType, defineOne, defineDestroy } = require('apemanmodel')
const validateDataType = require('../../validating/validate_data_type')
const validateDataGiven = require('../../validating/validate_data_given')
const co = require('co')
/** @lends BulkDestroyEndpoint */
class BulkDestroyEndpoint extends Endpoint {
/**
* @override
*/
getDefaultConfig () {
return {
name: 'bulkDestroy'
}
}
/**
* @override
*/
handle (ctx, next) {
const s = this
let succeed = s.bindSucceed(ctx)
let fail = s.bindFail(ctx)
let { state } = ctx
let { data } = state
return co(function * () {
let error = s.validate(data, state)
if (error) {
return fail(error)
}
let count = yield s.bulkDestroy(data, state)
return succeed({ count })
})
}
/**
* @override
*/
validate (data, state) {
let type = toType(state.model)
let dataGivenError = validateDataGiven.bulk(data)
if (dataGivenError) {
return dataGivenError
}
let typeErrors = validateDataType.bulk(data, type)
if (typeErrors) {
return typeErrors
}
}
bulkDestroy (data, state) {
let { model, transaction } = state
let destroy = defineDestroy(model, transaction)
let one = defineOne(model, transaction)
return co(function * () {
let count = 0
for (let d of data) {
let instance = yield one(d.id)
if (instance) {
yield destroy(instance)
count += 1
}
}
return count
})
}
}
module.exports = BulkDestroyEndpoint