salix/back/methods/dms/deleteTrashFiles.js

70 lines
2.0 KiB
JavaScript
Raw Permalink Normal View History

2022-08-10 10:13:31 +00:00
const UserError = require('vn-loopback/util/user-error');
2022-05-03 09:16:56 +00:00
const fs = require('fs-extra');
const path = require('path');
2024-05-21 13:11:32 +00:00
const isProduction = require('vn-loopback/server/boot/isProduction');
2022-05-03 09:16:56 +00:00
module.exports = Self => {
Self.remoteMethod('deleteTrashFiles', {
description: 'Deletes files that have trash type',
accessType: 'WRITE',
returns: {
type: 'object',
root: true
},
http: {
path: `/deleteTrashFiles`,
2022-09-13 11:53:44 +00:00
verb: 'POST'
2022-05-03 09:16:56 +00:00
}
});
Self.deleteTrashFiles = async options => {
2022-05-03 09:16:56 +00:00
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
2024-05-21 13:11:32 +00:00
if (!isProduction())
2022-10-17 11:13:14 +00:00
throw new UserError(`Action not allowed on the test environment`);
2022-05-03 09:16:56 +00:00
2022-10-17 11:13:14 +00:00
const models = Self.app.models;
const DmsContainer = models.DmsContainer;
2022-05-03 09:16:56 +00:00
2022-10-17 11:13:14 +00:00
const trashDmsType = await models.DmsType.findOne({
where: {code: 'trash'}
}, myOptions);
2022-08-10 10:13:31 +00:00
2023-01-16 14:18:24 +00:00
const date = Date.vnNew();
2022-10-17 11:13:14 +00:00
date.setMonth(date.getMonth() - 4);
2022-05-03 09:16:56 +00:00
2022-10-17 11:13:14 +00:00
const dmsToDelete = await models.Dms.find({
where: {
and: [
{dmsTypeFk: trashDmsType.id},
{created: {lt: date}}
]
}
}, myOptions);
2022-10-11 12:28:14 +00:00
2022-10-17 11:13:14 +00:00
for (let dms of dmsToDelete) {
const pathHash = DmsContainer.getHash(dms.id);
const dmsContainer = await DmsContainer.container(pathHash);
try {
const dstFile = path.join(dmsContainer.client.root, pathHash, dms.file);
2022-10-17 11:13:14 +00:00
await fs.unlink(dstFile);
} catch (err) {
if (err.code != 'ENOENT' && dms.file)
throw err;
2022-10-17 11:13:14 +00:00
}
await dms.destroy(myOptions);
2022-10-17 11:13:14 +00:00
const dstFolder = path.join(dmsContainer.client.root, pathHash);
try {
await fs.rmdir(dstFolder);
} catch (err) {
continue;
2022-05-03 09:16:56 +00:00
}
}
};
};