73 lines
2.2 KiB
JavaScript
73 lines
2.2 KiB
JavaScript
const UserError = require('vn-loopback/util/user-error');
|
|
const fs = require('fs-extra');
|
|
const path = require('path');
|
|
|
|
module.exports = Self => {
|
|
Self.remoteMethod('deleteTrashFiles', {
|
|
description: 'Deletes files that have trash type',
|
|
accessType: 'WRITE',
|
|
returns: {
|
|
type: 'object',
|
|
root: true
|
|
},
|
|
http: {
|
|
path: `/deleteTrashFiles`,
|
|
verb: 'GET'
|
|
}
|
|
});
|
|
|
|
Self.deleteTrashFiles = async options => {
|
|
const tx = await Self.beginTransaction({});
|
|
const myOptions = {};
|
|
|
|
if (typeof options == 'object')
|
|
Object.assign(myOptions, options);
|
|
|
|
if (!myOptions.transaction)
|
|
myOptions.transaction = tx;
|
|
|
|
try {
|
|
if (process.env.NODE_ENV == 'test')
|
|
throw new UserError(`Action not allowed on the test environment`);
|
|
|
|
const models = Self.app.models;
|
|
const DmsContainer = models.DmsContainer;
|
|
|
|
const trashDmsType = await models.DmsType.findOne({
|
|
where: {code: 'trash'}
|
|
}, myOptions);
|
|
|
|
const date = new Date();
|
|
date.setMonth(date.getMonth() - 4);
|
|
|
|
const dmsToDelete = await models.Dms.find({
|
|
where: {
|
|
and: [
|
|
{dmsTypeFk: trashDmsType.id},
|
|
{created: {lt: date}}
|
|
]
|
|
}
|
|
}, myOptions);
|
|
|
|
for (let dms of dmsToDelete) {
|
|
const pathHash = DmsContainer.getHash(dms.id);
|
|
const dmsContainer = await DmsContainer.container(pathHash);
|
|
const dstFile = path.join(dmsContainer.client.root, pathHash, dms.file);
|
|
const dstFolder = path.join(dmsContainer.client.root, pathHash);
|
|
await fs.unlink(dstFile);
|
|
try {
|
|
await fs.rmdir(dstFolder);
|
|
await dms.destroy(myOptions);
|
|
} catch (err) {
|
|
await dms.destroy(myOptions);
|
|
}
|
|
}
|
|
if (tx) await tx.commit();
|
|
} catch (e) {
|
|
if (tx) await tx.rollback();
|
|
|
|
throw e;
|
|
}
|
|
};
|
|
};
|