From 49da9d5d4833fd9b866040cce2525d2a68b1ab02 Mon Sep 17 00:00:00 2001 From: Divlo Date: Wed, 25 Mar 2020 23:30:33 +0100 Subject: [PATCH] back: DELETE /admin/functions/:id --- api/.gitignore | 1 + api/controllers/admin.js | 20 ++++++++++++++++++++ api/routes/admin.js | 7 ++++--- 3 files changed, 25 insertions(+), 3 deletions(-) diff --git a/api/.gitignore b/api/.gitignore index 0cc182c..ea03c17 100644 --- a/api/.gitignore +++ b/api/.gitignore @@ -19,6 +19,7 @@ .env.test.local .env.production.local /temp +/assets/images/ npm-debug.log* yarn-debug.log* diff --git a/api/controllers/admin.js b/api/controllers/admin.js index d029150..276510e 100644 --- a/api/controllers/admin.js +++ b/api/controllers/admin.js @@ -1,4 +1,5 @@ const path = require('path'); +const fs = require('fs'); const { validationResult } = require('express-validator'); const errorHandling = require('../assets/utils/errorHandling'); const { serverError } = require('../assets/config/errors'); @@ -30,4 +31,23 @@ exports.postFunction = (req, res, next) => { errorHandling(next, serverError); } }); +} + +exports.deleteFunction = async (req, res, next) => { + const { id } = req.params; + try { + const result = await Functions.findOne({ where: { id } }); + if (!result) { + return errorHandling(next, { message: "La fonction n'existe pas.", statusCode: 404 }); + } + if (result.image !== "/images/functions/default.png") { + const filePath = path.join(__dirname, '..', 'assets', result.image); + fs.unlinkSync(filePath); // supprime le fichier + } + await Functions.destroy({ where: { id } }); + res.status(200).json({ message: "La fonction a été correctement supprimé!"}); + } catch (error) { + console.log(error); + errorHandling(next, serverError); + } } \ No newline at end of file diff --git a/api/routes/admin.js b/api/routes/admin.js index 8a6f4b0..745f69b 100644 --- a/api/routes/admin.js +++ b/api/routes/admin.js @@ -10,9 +10,7 @@ const Categories = require('../models/categories'); const AdminRouter = Router(); // Permet de créé une fonction -AdminRouter.post('/functions', - isAuth, - isAdmin, +AdminRouter.post('/functions', isAuth, isAdmin, fileUpload({ useTempFiles: true, safeFileNames: true, @@ -76,4 +74,7 @@ AdminRouter.post('/functions', adminController.postFunction ); +// Supprime une fonction avec son id +AdminRouter.delete('/functions/:id', isAuth, isAdmin, adminController.deleteFunction); + module.exports = AdminRouter; \ No newline at end of file