👌 IMPROVE: backend - Hotfix suppression fichiers

This commit is contained in:
Divlo 2020-04-15 13:55:07 +02:00
parent 3d0488a605
commit 43d2180209
4 changed files with 29 additions and 30 deletions

View File

@ -1,19 +1,18 @@
const fs = require("fs"); const fs = require("fs");
const path = require("path"); const path = require("path");
function deleteFilesNameStartWith(pattern, dirPath = __dirname) { function deleteFilesNameStartWith(pattern, dirPath, callback) {
// Get all file names in directory fs.readdir(path.resolve(dirPath), (_error, fileNames) => {
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) { for (const name of fileNames) {
// If file name matches the pattern const splitedName = name.split('.');
if (name.startsWith(pattern) && name !== 'default.png') { if (splitedName.length === 2) {
console.log(name) const fileName = splitedName[0];
fs.unlinkSync(path.join(dirPath, name)); if (fileName === pattern && name !== 'default.png') {
return fs.unlink(path.join(dirPath, name), callback);
} }
} }
}
return callback();
}); });
} }

View File

@ -126,11 +126,13 @@ exports.putFunction = async (req, res, next) => {
if (splitedImageName.length !== 2) return errorHandling(next, serverError); if (splitedImageName.length !== 2) return errorHandling(next, serverError);
const imageName = slug + '.' + splitedImageName[1]; const imageName = slug + '.' + splitedImageName[1];
// Supprime les anciennes images // Supprime les anciennes images
deleteFilesNameStartWith(slug, path.join(__dirname, '..', 'assets', 'images', 'functions')); const functionPath = path.join(__dirname, '..', 'assets', 'images', 'functions');
image.mv(path.join(__dirname, '..', 'assets', 'images', 'functions', imageName), async (error) => { deleteFilesNameStartWith(slug, functionPath, () => {
image.mv(path.join(functionPath, imageName), async (error) => {
if (error) return errorHandling(next, serverError); if (error) return errorHandling(next, serverError);
return await handleEditFunction(res, resultFunction, { title, slug, description, type, categorieId }, imageName); return await handleEditFunction(res, resultFunction, { title, slug, description, type, categorieId }, imageName);
}); });
});
} else { } else {
return await handleEditFunction(res, resultFunction, { title, slug, description, type, categorieId }); return await handleEditFunction(res, resultFunction, { title, slug, description, type, categorieId });
} }

View File

@ -35,14 +35,14 @@ async function handleEditUser(res, { name, email, biography, isPublicEmail }, us
user.biography = biography; user.biography = biography;
} }
user.isPublicEmail = isPublicEmail; user.isPublicEmail = isPublicEmail;
if (logoName != undefined) { if (logoName != undefined && `/images/users/${logoName}` !== user.logo) {
user.logo = `/images/users/${logoName}`; user.logo = `/images/users/${logoName}`;
} }
await user.save(); await user.save();
return res.status(200).json({ id: user.id, name: user.name, email: user.email, biography: user.biography, logo: user.logo, isPublicEmail: user.isPublicEmail, isAdmin: user.isAdmin, createdAt: user.createdAt }); return res.status(200).json({ id: user.id, name: user.name, email: user.email, biography: user.biography, logo: user.logo, isPublicEmail: user.isPublicEmail, isAdmin: user.isAdmin, createdAt: user.createdAt });
} }
exports.putUser = (req, res, next) => { exports.putUser = async (req, res, next) => {
const { name, email, biography, isPublicEmail } = req.body; const { name, email, biography, isPublicEmail } = req.body;
const logo = req.files.logo; const logo = req.files.logo;
const errors = validationResult(req); const errors = validationResult(req);
@ -58,26 +58,24 @@ exports.putUser = (req, res, next) => {
)) { )) {
return errorHandling(next, { message:"Le profil doit avoir une image valide (PNG, JPG, GIF) et moins de 5mo.", statusCode: 400 }); return errorHandling(next, { message:"Le profil doit avoir une image valide (PNG, JPG, GIF) et moins de 5mo.", statusCode: 400 });
} }
const logoName = name + req.userId + uuid.v4() + logo.name; const splitedLogoName = logo.name.split('.');
if (splitedLogoName.length !== 2) return errorHandling(next, serverError);
const logoName = name + req.userId + '.' + splitedLogoName[1];
// Supprime les anciens logo // Supprime les anciens logo
try { try {
deleteFilesNameStartWith(`${name + req.userId}`, path.join(__dirname, '..', 'assets', 'images', 'users')); deleteFilesNameStartWith(`${name + req.userId}`, path.join(__dirname, '..', 'assets', 'images', 'users'), async () => {
} catch (error) { logo.mv(path.join(__dirname, '..', 'assets', 'images', 'users', logoName), async (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); if (error) return errorHandling(next, serverError);
try { return await handleEditUser(res, { name, email, biography, isPublicEmail }, req.userId, logoName);
return handleEditUser(res, { name, email, biography, isPublicEmail }, req.userId, logoName); });
});
} catch (error) { } catch (error) {
console.log(error); console.log(error);
return errorHandling(next, serverError); return errorHandling(next, serverError);
} }
});
} else { } else {
try { try {
return handleEditUser(res, { name, email, biography, isPublicEmail }, req.userId, null); return await handleEditUser(res, { name, email, biography, isPublicEmail }, req.userId, null);
} catch (error) { } catch (error) {
console.log(error); console.log(error);
return errorHandling(next, serverError); return errorHandling(next, serverError);

View File

@ -97,7 +97,7 @@ AdminRouter.route('/functions')
AdminRouter.route('/functions/:id') AdminRouter.route('/functions/:id')
// Modifier information basique d'une fonction // Modifie information basique d'une fonction
.put(isAuth, isAdmin, .put(isAuth, isAdmin,
fileUpload({ fileUpload({
useTempFiles: true, useTempFiles: true,
@ -180,7 +180,7 @@ AdminRouter.route('/categories/:id')
// Modifier une catégorie avec son id // Modifier une catégorie avec son id
.put(isAuth, isAdmin, adminController.putCategory) .put(isAuth, isAdmin, adminController.putCategory)
// Supprime une fonction avec son id // Supprime une catégorie avec son id
.delete(isAuth, isAdmin, adminController.deleteCategory); .delete(isAuth, isAdmin, adminController.deleteCategory);
module.exports = AdminRouter; module.exports = AdminRouter;