backend: PUT /admin/functions/:id

This commit is contained in:
Divlo 2020-04-13 22:11:34 +02:00
parent 20d89d7002
commit 3d0488a605
2 changed files with 141 additions and 9 deletions

View File

@ -7,6 +7,20 @@ const Functions = require('../models/functions');
const Categories = require('../models/categories'); const Categories = require('../models/categories');
const helperQueryNumber = require('../assets/utils/helperQueryNumber'); const helperQueryNumber = require('../assets/utils/helperQueryNumber');
const Sequelize = require('sequelize'); const Sequelize = require('sequelize');
const deleteFilesNameStartWith = require('../assets/utils/deleteFilesNameStartWith');
const handleEditFunction = async (res, resultFunction, { title, slug, description, type, categorieId }, imageName = false) => {
resultFunction.title = title;
resultFunction.slug = slug;
resultFunction.description = description;
resultFunction.type = type;
resultFunction.categorieId = categorieId;
if (imageName) {
resultFunction.image = `/images/functions/${imageName}`;
}
const result = await resultFunction.save();
res.status(200).json({ message: "La fonction a bien été modifié!", result });
}
exports.getFunctions = (req, res, next) => { exports.getFunctions = (req, res, next) => {
const page = helperQueryNumber(req.query.page, 1); const page = helperQueryNumber(req.query.page, 1);
@ -78,6 +92,54 @@ exports.postFunction = (req, res, next) => {
}); });
} }
exports.putFunction = async (req, res, next) => {
const { id } = req.params;
const { title, slug, description, type, categorieId } = req.body;
const image = req.files.image;
const errors = validationResult(req);
if (!errors.isEmpty()) {
return errorHandling(next, { message: errors.array()[0].msg, statusCode: 400 });
}
try {
// Vérifie si la fonction existe
const resultFunction = await Functions.findOne({ where: { id } });
if (!resultFunction) {
return errorHandling(next, { message: "La fonction n'existe pas.", statusCode: 404 });
}
// Vérifie si le slug existe déjà
const FunctionSlug = await Functions.findOne({ where: { slug } });
if (!FunctionSlug && FunctionSlug.id != resultFunction.id) {
return errorHandling(next, { message: "Le slug existe déjà...", statusCode: 404 });
}
// Sauvegarde de la fonction
if (image != undefined) {
if (image.truncated && (
image.mimetype !== 'image/png' ||
image.mimetype !== 'image/jpg' ||
image.mimetype !== 'image/jpeg'
)) {
return errorHandling(next, { message:"La fonction doit avoir une image valide.", statusCode: 400 });
}
const splitedImageName = image.name.split('.');
if (splitedImageName.length !== 2) return errorHandling(next, serverError);
const imageName = slug + '.' + splitedImageName[1];
// Supprime les anciennes images
deleteFilesNameStartWith(slug, path.join(__dirname, '..', 'assets', 'images', 'functions'));
image.mv(path.join(__dirname, '..', 'assets', 'images', 'functions', imageName), async (error) => {
if (error) return errorHandling(next, serverError);
return await handleEditFunction(res, resultFunction, { title, slug, description, type, categorieId }, imageName);
});
} else {
return await handleEditFunction(res, resultFunction, { title, slug, description, type, categorieId });
}
} catch (error) {
console.log(error);
return errorHandling(next, serverError);
}
}
exports.deleteFunction = async (req, res, next) => { exports.deleteFunction = async (req, res, next) => {
const { id } = req.params; const { id } = req.params;
try { try {

View File

@ -97,6 +97,76 @@ AdminRouter.route('/functions')
AdminRouter.route('/functions/:id') AdminRouter.route('/functions/:id')
// Modifier information basique d'une fonction
.put(isAuth, isAdmin,
fileUpload({
useTempFiles: true,
safeFileNames: true,
preserveExtension: Number,
limits: { fileSize: 5 * 1024 * 1024 }, // 5mb,
parseNested: true
}),
[
body('title')
.not()
.isEmpty()
.withMessage("La fonction doit avoir un titre.")
.isLength({ max: 100 })
.withMessage("Le titre est trop long.")
.custom(((title) => {
if (title === 'undefined') {
return Promise.reject("La fonction doit avoir un titre.");
}
return true;
})),
body('slug')
.not()
.isEmpty()
.withMessage("La fonction doit avoir un slug.")
.isLength({ max: 100 })
.withMessage("Le slug est trop long.")
.custom(((slug) => {
if (slug === 'undefined') {
return Promise.reject("La fonction doit avoir un slug.");
}
return true;
})),
body('description')
.not()
.isEmpty()
.withMessage("La fonction doit avoir une description.")
.isLength({ max: 255, min: 1 })
.withMessage("La description est trop longue.")
.custom(((description) => {
if (description === 'undefined') {
return Promise.reject("La fonction doit avoir une description.");
}
return true;
})),
body('categorieId')
.not()
.isEmpty()
.withMessage("La fonction doit avoir une catégorie.")
.custom(async (categorieId) => {
try {
const categorieFound = await Categories.findOne({ where: { id: parseInt(categorieId) } });
if (!categorieFound) {
return Promise.reject("La catégorie n'existe pas!");
}
} catch (error) {
console.log(error);
}
return true;
}),
body('type')
.custom((type) => {
if (!(type === 'article' || type === 'form' || type === 'page')) {
return Promise.reject('Le type de la fonction peut être : article, form ou page.');
}
return true;
})
], adminController.putFunction)
// Supprime une fonction avec son id // Supprime une fonction avec son id
.delete(isAuth, isAdmin, adminController.deleteFunction); .delete(isAuth, isAdmin, adminController.deleteFunction);