UNPKG

apeman-app-rest

Version:
84 lines (71 loc) 1.9 kB
/** * Endpoint for relation destroy * @augments Endpoint * @class RelationDestroyEndpoint */ 'use strict' const Endpoint = require('./endpoint') const BulkRelationDestroyEndpoint = require('./bulk/bulk_relation_destroy_endpoint') const { defineRelationDestroy } = require('apemanmodel') const validateModelExists = require('../validating/validate_model_exists') const co = require('co') /** @lends RelationDestroyEndpoint */ class RelationDestroyEndpoint extends Endpoint { /** * @override */ getDefaultConfig () { return { name: 'relationDestroy' } } /** * @override */ handle (ctx, next) { const s = this let succeed = s.bindSucceed(ctx) let fail = s.bindFail(ctx) let { state } = ctx let { data, id } = state let isBulk = Array.isArray(data) if (isBulk) { return s.handleBulk(ctx, next) } return co(function * () { let error = s.validate(data, state) if (error) { return fail(error) } let count = yield s.relationDestroy(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 } handleBulk (ctx, next) { const s = this let config = Object.assign({}, s.config, { name: 'bulkRelationDestroy' }) return new BulkRelationDestroyEndpoint(config).handle(ctx, next) } relationDestroy (id, data, state) { let { model, association, transaction } = state let relationDestroy = defineRelationDestroy(model, association, transaction) return co(function * () { return yield relationDestroy(id, data) }) } } Object.assign(RelationDestroyEndpoint, {}) module.exports = RelationDestroyEndpoint