diff --git a/modules/uploads/repositories/uploads.repository.js b/modules/uploads/repositories/uploads.repository.js index d0469bde2..db1017882 100644 --- a/modules/uploads/repositories/uploads.repository.js +++ b/modules/uploads/repositories/uploads.repository.js @@ -68,3 +68,42 @@ exports.deleteMany = async (filter) => { }); return { deletedCount: uploads.length }; }; + +/** + * @desc Function to purge uploads by kind if they are not referenced in another collection + * @param {String} kind - metadata kind to match + * @param {collection} collection - name of the collection to check reference presence + * @param {String} key - name of the key to check id + * @return {Object} confirmation of delete + */ +exports.purge = async (kind, collection, key) => { + const toDelete = await Uploads.aggregate( + [ + { + $match: { + 'metadata.kind': kind, + }, + }, + { + $lookup: { + from: collection, + localField: 'filename', + foreignField: key, + as: 'references', + }, + }, + { + $match: { + references: [], + }, + }, + ], + ); + toDelete.forEach(async (id) => { + Attachment.unlink(id, (err, unlinked) => { + if (err) throw new AppError('Upload: delete error', { code: 'REPOSITORY_ERROR', details: err }); + return unlinked; + }); + }); + return { deletedCount: toDelete.length }; +}; diff --git a/scripts/purgeUploads.js b/scripts/purgeUploads.js new file mode 100644 index 000000000..1ffdc590c --- /dev/null +++ b/scripts/purgeUploads.js @@ -0,0 +1,31 @@ +/** + * Module dependencies + */ +const chalk = require('chalk'); +const path = require('path'); + +const mongooseService = require(path.resolve('./lib/services/mongoose')); + +/** + * Work + */ + +const purge = async () => { + try { + await mongooseService.connect(); + await mongooseService.loadModels(); + + const uploadRepository = require(path.resolve('./modules/uploads/repositories/uploads.repository')); + const result = await uploadRepository.purge('avatar', 'users', 'avatar'); + console.log(chalk.bold.blue(`Uploads purged ${result.deletedCount} avatar`)); + } catch (err) { + console.log(chalk.bold.red(`Error ${err}`)); + } + + setTimeout(() => { + console.log(chalk.green('Finish purge of uploads in mongoDB')); + process.exit(0); + }, 1000); +}; + +purge();