refactor: deleteOldFiles in claim
gitea/salix/pipeline/head This commit looks good Details

This commit is contained in:
Vicent Llopis 2022-04-20 14:46:37 +02:00
parent 6e999302bf
commit 5db20ee3e2
2 changed files with 23 additions and 19 deletions

View File

@ -89,7 +89,7 @@
"name": "claimStorage",
"connector": "loopback-component-storage",
"provider": "filesystem",
"root": "./storage/claim",
"root": "./storage/dms",
"maxFileSize": "31457280",
"allowedContentTypes": [
"image/png",

View File

@ -3,7 +3,7 @@ const path = require('path');
module.exports = Self => {
Self.remoteMethodCtx('deleteOldFiles', {
description: 'Delete files that are 6 months old from "./storage/claim"',
description: 'Delete files that are 6 months old from dms',
accessType: 'WRITE',
returns: {
type: 'object',
@ -15,7 +15,7 @@ module.exports = Self => {
}
});
Self.deleteOldFiles = async options => {
Self.deleteOldFiles = async(ctx, options) => {
const tx = await Self.beginTransaction({});
const myOptions = {};
@ -26,27 +26,31 @@ module.exports = Self => {
myOptions.transaction = tx;
try {
const claimContainer = './storage/claim';
const folders = fs.readdirSync(claimContainer);
let file;
let srcFile;
const models = Self.app.models;
const sixMonthsAgo = new Date();
sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 6);
for (let i in folders) {
const srcFoulder = path.join(claimContainer, folders[i]);
[file] = fs.readdirSync(srcFoulder);
if (!file) file = '';
srcFile = path.join(srcFoulder, file);
const {birthtime} = fs.statSync(srcFile);
const sixMonthsAgo = new Date();
sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 6);
const claimDmsType = await models.DmsType.findOne({where: {code: 'claim'}}, myOptions);
const oldDms = await models.Dms.find({
where: {
and: [{
created: {lt: sixMonthsAgo}}, {
dmsTypeFk: claimDmsType.id
}]
}
});
if (birthtime < sixMonthsAgo)
fs.rmdir(srcFoulder, {recursive: true});
for (let dms of oldDms) {
const ClaimContainer = models.ClaimContainer;
const pathHash = await ClaimContainer.getHash(dms.id);
const claimContainer = await ClaimContainer.container(pathHash);
const dstFile = path.join(claimContainer.client.root, pathHash, dms.file);
await fs.unlink(dstFile);
await models.ClaimDms.removeFile(ctx, dms.id);
}
if (tx) await tx.commit();
return claimContainer;
return oldDms;
} catch (e) {
if (tx) await tx.rollback();