module.exports = function(Self) { Self.validate('default', isEnabled, {message: 'No se puede poner predeterminado un consignatario desactivado'}); function isEnabled(err) { if (!this.isEnabled && this.isDefaultAddress) err(); } Self.beforeRemote('create', function(ctx, modelInstance, next) { var data = ctx.req.body; create(data, next); }); function create(data, next) { if (data.isDefaultAddress) { removeAllDefault(data.client, next); } else { next(); } } Self.beforeRemote('prototype.patchAttributes', function(ctx, modelInstance, next) { let newData = ctx.req.body; newData.id = ctx.req.params.id; getAddress(ctx, newData, next); }); Self.beforeRemote('findById', function(ctx, modelInstance, next) { ctx.args.filter = { "include": { "relation": "province", "scope": { "fields": ["id", "name"] } } }; next(); }); function getAddress(ctx, newData, next) { Self.findOne({where: {id: newData.id}}, (_, oldData) => { if (oldData) callbackGetAddress(ctx, newData, oldData, next); }); } function callbackGetAddress(ctx, newData, oldData, next) { if (newData.isDefaultAddress) { removeAllDefault(oldData.client, next); } else if (oldData.isDefaultAddress && newData.hasOwnProperty('isDefaultAddress') && !newData.isDefaultAddress) { next(generateErrorDefaultAddress()); } else next(); } function removeAllDefault(client, next) { Self.updateAll({clientFk: client.id, isDefaultAddress: {neq: 0}}, {isDefaultAddress: false}, next); } function generateErrorDefaultAddress() { var error = new Error(); error.message = "No se puede desmarcar el consignatario predeterminado"; error.status = 500; return error; } };