frontend et backend: Crée une nouvelle fonction
This commit is contained in:
@ -4,6 +4,50 @@ const { validationResult } = require('express-validator');
|
||||
const errorHandling = require('../assets/utils/errorHandling');
|
||||
const { serverError } = require('../assets/config/errors');
|
||||
const Functions = require('../models/functions');
|
||||
const Categories = require('../models/categories');
|
||||
const helperQueryNumber = require('../assets/utils/helperQueryNumber');
|
||||
const Sequelize = require('sequelize');
|
||||
|
||||
exports.getFunctions = (req, res, next) => {
|
||||
const page = helperQueryNumber(req.query.page, 1);
|
||||
const limit = helperQueryNumber(req.query.limit, 10);
|
||||
const categoryId = helperQueryNumber(req.query.categoryId, 0);
|
||||
let search = req.query.search;
|
||||
try { search = search.toLowerCase(); } catch {}
|
||||
const offset = (page - 1) * limit;
|
||||
Functions.findAndCountAll({
|
||||
limit,
|
||||
offset,
|
||||
where: {
|
||||
// Trie par catégorie
|
||||
... (categoryId !== 0) && { categorieId: categoryId },
|
||||
// Recherche
|
||||
... (search != undefined) && {
|
||||
[Sequelize.Op.or]: [
|
||||
{ title: Sequelize.where(Sequelize.fn('LOWER', Sequelize.col('title')), 'LIKE', `%${search}%`) },
|
||||
{ slug: Sequelize.where(Sequelize.fn('LOWER', Sequelize.col('slug')), 'LIKE', `%${search}%`) },
|
||||
{ description: Sequelize.where(Sequelize.fn('LOWER', Sequelize.col('description')), 'LIKE', `%${search}%`) }
|
||||
]
|
||||
}
|
||||
},
|
||||
include: [
|
||||
{ model: Categories, attributes: ["name", "color"] }
|
||||
],
|
||||
attributes: {
|
||||
exclude: ["updatedAt", "utilizationForm", "article", "isOnline"]
|
||||
},
|
||||
order: [['createdAt', 'DESC']]
|
||||
})
|
||||
.then((result) => {
|
||||
const { count, rows } = result;
|
||||
const hasMore = (page * limit) < count;
|
||||
return res.status(200).json({ totalItems: count, hasMore, rows });
|
||||
})
|
||||
.catch((error) => {
|
||||
console.log(error);
|
||||
return errorHandling(next, serverError);
|
||||
});
|
||||
}
|
||||
|
||||
exports.postFunction = (req, res, next) => {
|
||||
const { title, slug, description, type, categorieId } = req.body;
|
||||
@ -19,7 +63,9 @@ exports.postFunction = (req, res, next) => {
|
||||
)) {
|
||||
return errorHandling(next, { message:"La fonction doit avoir une image valide.", statusCode: 400 });
|
||||
}
|
||||
const imageName = slug + image.name;
|
||||
const splitedImageName = image.name.split('.');
|
||||
if (splitedImageName.length !== 2) return errorHandling(next, serverError);
|
||||
const imageName = slug + '.' + splitedImageName[1];
|
||||
image.mv(path.join(__dirname, '..', 'assets', 'images', 'functions') + '/' + imageName, async (error) => {
|
||||
if (error) return errorHandling(next, serverError);
|
||||
try {
|
||||
|
@ -18,6 +18,6 @@ module.exports = (req, _res, next) => {
|
||||
})
|
||||
.catch((error) => {
|
||||
console.log(error);
|
||||
errorHandling(next, serverError);
|
||||
return errorHandling(next, serverError);
|
||||
});
|
||||
}
|
@ -9,70 +9,95 @@ const Categories = require('../models/categories');
|
||||
|
||||
const AdminRouter = Router();
|
||||
|
||||
// Permet de créé une fonction
|
||||
AdminRouter.post('/functions', 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."),
|
||||
body('slug')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage("La fonction doit avoir un slug.")
|
||||
.isLength({ max: 100 })
|
||||
.withMessage("Le slug est trop long.")
|
||||
.custom((async (slug) => {
|
||||
try {
|
||||
const FunctionSlug = await Functions.findOne({ where: { slug } });
|
||||
if (FunctionSlug) {
|
||||
return Promise.reject("Le slug existe déjà...");
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
return true;
|
||||
})),
|
||||
body('description')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage("La fonction doit avoir une description.")
|
||||
.isLength({ max: 255 })
|
||||
.withMessage("La description est trop longue."),
|
||||
body('categorieId')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage("La fonction doit avoir une catégorie.")
|
||||
.custom(async (categorieId) => {
|
||||
try {
|
||||
const categorieFound = await Categories.findOne({ where: { id: 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.postFunction);
|
||||
AdminRouter.route('/functions')
|
||||
|
||||
// Supprime une fonction avec son id
|
||||
AdminRouter.delete('/functions/:id', isAuth, isAdmin, adminController.deleteFunction);
|
||||
// Récupère les fonctions
|
||||
.get(isAuth, isAdmin, adminController.getFunctions)
|
||||
|
||||
// Permet de créé une fonction
|
||||
.post(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;
|
||||
}))
|
||||
.custom((async (slug) => {
|
||||
try {
|
||||
const FunctionSlug = await Functions.findOne({ where: { slug } });
|
||||
if (FunctionSlug) {
|
||||
return Promise.reject("Le slug existe déjà...");
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
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.postFunction);
|
||||
|
||||
AdminRouter.route('/functions/:id')
|
||||
|
||||
// Supprime une fonction avec son id
|
||||
.delete(isAuth, isAdmin, adminController.deleteFunction);
|
||||
|
||||
module.exports = AdminRouter;
|
Reference in New Issue
Block a user