47 lines
1.7 KiB
JavaScript
47 lines
1.7 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 crudObject => {
|
|
let promises = [];
|
|
let transaction = await Model.beginTransaction({});
|
|
let options = {transaction: transaction};
|
|
|
|
try {
|
|
if (crudObject.delete && crudObject.delete.length) {
|
|
promises.push(Model.destroyAll({id: {inq: crudObject.delete}}, options));
|
|
}
|
|
if (crudObject.create && crudObject.create.length) {
|
|
promises.push(Model.create(crudObject.create, options));
|
|
}
|
|
if (crudObject.update) {
|
|
crudObject.update.forEach(toUpdate => {
|
|
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;
|
|
}
|
|
};
|
|
};
|
|
};
|