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

47 lines
1.7 KiB
JavaScript
Raw Normal View History

2018-02-27 13:55:59 +00:00
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();
2018-04-04 14:41:06 +00:00
throw Array.isArray(e) ? e[0] : e;
2018-02-27 13:55:59 +00:00
}
};
};
};