-
Notifications
You must be signed in to change notification settings - Fork 3
[Node] Supprimer les fichiers inutiles stockés sur S3
gregoirethomazeau edited this page May 25, 2023
·
1 revision
Créer un fichier à la racine de l'API avec le code suivant :
import './module_alias';
import { S3 } from '#server/utils/s3';
import config from '#server/config';
import { DeleteObjectCommand, ListObjectsCommand } from '@aws-sdk/client-s3';
import { sequelize } from '#db/sequelize';
import { QueryTypes } from 'sequelize';
(async () => {
// on récupère la liste des clés sur le bucket
const bucketFiles = await S3.send(new ListObjectsCommand({
Bucket: config.S3.bucket,
}));
// on récupère les clés dans la BDD
const keys = (await sequelize.query(
`SELECT
original_file_key,
preview_file_key
FROM attachments`,
{
type: QueryTypes.SELECT,
},
)).map((attachment: any) => [attachment.original_file_key, attachment.preview_file_key]).flat().filter(el => el !== null);
// on supprime les fichiers sur le bucket non présents dans la BDD
bucketFiles.Contents.forEach((file) => {
if (!keys.includes(file.Key)) {
S3.send(new DeleteObjectCommand({
Bucket: config.S3.bucket,
Key: file.Key,
}));
}
});
})();
Exécuter le fichier avec la commande yarn ts-node