From 3ed605af1b6cfa2b61d4b1c0962d3df288c3d86f Mon Sep 17 00:00:00 2001 From: Divlo Date: Tue, 7 Apr 2020 17:15:01 +0200 Subject: [PATCH] backend: PUT /users - Supprime les anciens logo --- api/assets/utils/deleteFilesNameStartWith.js | 20 ++++++++++++++++++++ api/controllers/users.js | 10 +++++++++- 2 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 api/assets/utils/deleteFilesNameStartWith.js diff --git a/api/assets/utils/deleteFilesNameStartWith.js b/api/assets/utils/deleteFilesNameStartWith.js new file mode 100644 index 0000000..b2940d6 --- /dev/null +++ b/api/assets/utils/deleteFilesNameStartWith.js @@ -0,0 +1,20 @@ +const fs = require("fs"); +const path = require("path"); + +function deleteFilesNameStartWith(pattern, dirPath = __dirname) { + // Get all file names in directory + fs.readdir(path.resolve(dirPath), (err, fileNames) => { + if (err) throw err; + console.log(dirPath); + // Iterate through the found file names + for (const name of fileNames) { + // If file name matches the pattern + if (name.startsWith(pattern)) { + console.log(name) + fs.unlinkSync(path.join(dirPath, name)); + } + } + }); +} + +module.exports = deleteFilesNameStartWith; \ No newline at end of file diff --git a/api/controllers/users.js b/api/controllers/users.js index 6ebe121..04bba56 100644 --- a/api/controllers/users.js +++ b/api/controllers/users.js @@ -14,6 +14,7 @@ const Favorites = require('../models/favorites'); const Functions = require('../models/functions'); const Categories = require('../models/categories'); const Comments = require('../models/comments'); +const deleteFilesNameStartWith = require('../assets/utils/deleteFilesNameStartWith'); async function handleEditUser(res, { name, email, biography, isPublicEmail }, userId, logoName) { const user = await Users.findOne({ where: { id: userId } }); @@ -44,7 +45,14 @@ exports.putUser = (req, res, next) => { )) { return errorHandling(next, { message:"Le profil doit avoir une image valide.", statusCode: 400 }); } - const logoName = name + uuid.v4() + logo.name; + const logoName = name + req.userId + uuid.v4() + logo.name; + // Supprime les anciens logo + try { + deleteFilesNameStartWith(`${name + req.userId}`, path.join(__dirname, '..', 'assets', 'images', 'users')); + } catch (error) { + console.log(error); + return errorHandling(next, serverError); + } logo.mv(path.join(__dirname, '..', 'assets', 'images', 'users') + '/' + logoName, async (error) => { if (error) return errorHandling(next, serverError); try {