Skip to content

Commit

Permalink
feat(uploads): add purge script example ✨
Browse files Browse the repository at this point in the history
  • Loading branch information
PierreBrisorgueil committed May 4, 2020
1 parent 6c1fe29 commit 363cd28
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
39 changes: 39 additions & 0 deletions modules/uploads/repositories/uploads.repository.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
};
31 changes: 31 additions & 0 deletions scripts/purgeUploads.js
Original file line number Diff line number Diff line change
@@ -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();

0 comments on commit 363cd28

Please sign in to comment.