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 crudObject => {
2018-02-27 13:55:59 +00:00
let promises = [];
let transaction = await Model.beginTransaction({});
let options = {transaction: transaction};
2018-02-27 13:55:59 +00:00
try {
if (crudObject.delete && crudObject.delete.length) {
promises.push(Model.destroyAll({id: {inq: crudObject.delete}}, options));
2018-02-27 13:55:59 +00:00
}
if (crudObject.create && crudObject.create.length) {
promises.push(Model.create(crudObject.create, options));
2018-02-27 13:55:59 +00:00
}
if (crudObject.update) {
crudObject.update.forEach(toUpdate => {
2018-02-27 13:55:59 +00:00
promises.push(Model.upsert(toUpdate, options));
});
}
await Promise.all(promises);
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw Array.isArray(error) ? error[0] : error;
2018-02-27 13:55:59 +00:00
}
};
};
};