salix/services/loopback/common/methods/vnModel/installCrudModel.js

47 lines
1.6 KiB
JavaScript

module.exports = function(Self) {
Self.installCrudModel = function(methodName) {
let Model = this;
Model.remoteMethod(methodName, {
description: 'create, update or delete model',
accessType: 'WRITE',
accepts: [
{
arg: 'crudStruct',
type: 'Object',
require: true,
description: 'object with instances of model to create, update or delete, Example: {create: [], update: [], delete: []}',
http: {source: 'body'}
}
],
http: {
path: `/${methodName}`,
verb: 'post'
}
});
Model[methodName] = async crudStruct => {
let promises = [];
let tx = await Model.beginTransaction({});
let options = {transaction: tx};
try {
if (crudStruct.delete && crudStruct.delete.length) {
promises.push(Model.destroyAll({id: {inq: crudStruct.delete}}, options));
}
if (crudStruct.create.length) {
promises.push(Model.create(crudStruct.create, options));
}
if (crudStruct.update.length) {
crudStruct.update.forEach(toUpdate => {
promises.push(Model.upsert(toUpdate, options));
});
}
await Promise.all(promises);
await tx.commit();
} catch (e) {
await tx.rollback();
throw e;
}
};
};
};