delete: transaction
gitea/salix/pipeline/head This commit looks good Details

This commit is contained in:
Vicent Llopis 2022-10-17 13:13:14 +02:00
parent 42583a4a16
commit e6481af3a9
1 changed files with 33 additions and 44 deletions

View File

@ -17,61 +17,50 @@ module.exports = Self => {
}); });
Self.deleteTrashFiles = async options => { Self.deleteTrashFiles = async options => {
let tx;
const myOptions = {}; const myOptions = {};
if (typeof options == 'object') if (typeof options == 'object')
Object.assign(myOptions, options); Object.assign(myOptions, options);
if (!myOptions.transaction) { if (process.env.NODE_ENV == 'test')
tx = await Self.beginTransaction({}); throw new UserError(`Action not allowed on the test environment`);
myOptions.transaction = tx;
}
try { const models = Self.app.models;
if (process.env.NODE_ENV == 'test') const DmsContainer = models.DmsContainer;
throw new UserError(`Action not allowed on the test environment`);
const models = Self.app.models; const trashDmsType = await models.DmsType.findOne({
const DmsContainer = models.DmsContainer; where: {code: 'trash'}
}, myOptions);
const trashDmsType = await models.DmsType.findOne({ const date = new Date();
where: {code: 'trash'} date.setMonth(date.getMonth() - 4);
}, myOptions);
const date = new Date(); const dmsToDelete = await models.Dms.find({
date.setMonth(date.getMonth() - 4); where: {
and: [
const dmsToDelete = await models.Dms.find({ {dmsTypeFk: trashDmsType.id},
where: { {created: {lt: date}}
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);
try {
await fs.unlink(dstFile);
} catch (err) {
continue;
}
const dstFolder = path.join(dmsContainer.client.root, pathHash);
try {
await fs.rmdir(dstFolder);
} catch (err) {}
await dms.destroy(myOptions);
} }
if (tx) await tx.commit(); }, myOptions);
} catch (e) {
if (tx) await tx.rollback();
throw e; 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);
try {
await fs.unlink(dstFile);
} catch (err) {
continue;
}
const dstFolder = path.join(dmsContainer.client.root, pathHash);
try {
await fs.rmdir(dstFolder);
} catch (err) {
continue;
}
await dms.destroy(myOptions);
} }
}; };
}; };