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