salix/back/methods/dms/removeFile.js

62 lines
1.9 KiB
JavaScript

const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('removeFile', {
description: 'Makes a logical delete moving a file to a trash folder',
accessType: 'WRITE',
accepts: [{
arg: 'id',
type: 'Number',
description: 'The document id',
http: {source: 'path'}
}],
returns: {
type: 'Object',
root: true
},
http: {
path: `/:id/removeFile`,
verb: 'POST'
}
});
Self.removeFile = async(ctx, id, options) => {
const models = Self.app.models;
let tx;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
try {
let modelDms = null;
if (myOptions.model) {
modelDms = await models[myOptions.model].findById(id, null, myOptions);
id = modelDms.dmsFk;
}
const targetDms = await models.Dms.findById(id, null, myOptions);
const trashDmsType = await models.DmsType.findOne({
where: {code: 'trash'}
}, myOptions);
const hasWriteRole = await models.DmsType.hasWriteRole(ctx, targetDms.dmsTypeFk, myOptions);
if (!hasWriteRole)
throw new UserError(`You don't have enough privileges`);
await targetDms.updateAttribute('dmsTypeFk', trashDmsType.id, myOptions);
if (tx) await tx.commit();
if (modelDms) modelDms.destroy(myOptions);
return targetDms;
} catch (e) {
if (tx) await tx.rollback();
throw e;
}
};
};