Mise à jour de controleurs, models et routes

This commit is contained in:
Rampeur
2025-08-19 05:13:24 +02:00
parent f8d8ff2329
commit b1513dccdd
21 changed files with 905 additions and 113 deletions
+272 -54
View File
@@ -1,60 +1,278 @@
const { ArticleService } = require('../services');
//const { where } = require("sequelize");
const asyncHandler = require("../middlewares/asyncHandler");
const Article = require("../database/models/mysql/Article");
const Tag = require("../database/models/mysql/Tag");
const User = require("../database/models/mysql/User");
const ErrorResponse = require("../utils/errorResponse");
const slug = require("slug");
const createArticle = async (req, res) => {
try {
const { slug, title, description, body, authorId } = req.body;
const {
appendFollowers,
appendFavorites,
appendTagList,
} = require("../utils/helpers");
const article = await ArticleService.createArticle({
slug,
title,
description,
body,
authorId
});
const includeOptions = [
{
model: Tag,
as: "tagLists",
attributes: ["name"],
through: { attributes: [] },
},
{ model: User, as: "author", attributes: { exclude: ["email", "password"] } },
];
res.status(201).json({
message: 'Article created successfully',
data: article,
});
} catch (err) {
res.status(500).json({
message: 'something went wrong while creating article',
error: err.message,
});
module.exports.getArticle = asyncHandler(async (req, res, next) => {
const { slug } = req.params;
let article = await ArticleService.getArticleBySlug(slug);
if (!article) {
return next(new ErrorResponse("Article not found", 404));
}
let tagList = article.tagNameTagTagLists;
//let author = article.author;
article = article.toJSONFor();
article.tagList = tagList;
//article.author = author
res.status(200).json({ article: article });
});
module.exports.getArticles = asyncHandler(async (req, res) => {
const { tag, author, favorited, limit = 20, offset = 0 } = req.query;
const { loggedUser } = req;
const searchOptions = {
include: [
{
model: Tag,
as: "tagLists",
attributes: ["name"],
through: { attributes: [] }, // ? this will remove the rows from the join table
// where: tag ? { name: tag } : {},
...(tag && { where: { name: tag } }),
},
{
model: User,
as: "author",
attributes: { exclude: ["password", "email"] },
// where: author ? { username: author } : {},
...(author && { where: { username: author } }),
},
],
limit: parseInt(limit),
offset: parseInt(offset),
order: [["createdAt", "DESC"]],
distinct: true,
};
let articles = { rows: [], count: 0 };
if (favorited) {
const user = await User.findOne({ where: { username: favorited } });
articles.rows = await user.getFavorites(searchOptions);
articles.count = await user.countFavorites();
} else {
articles = await Article.findAndCountAll(searchOptions);
}
for (let article of articles.rows) {
const articleTags = await article.getTagLists();
// const articleTags = article.tagLists;
appendTagList(articleTags, article);
await appendFollowers(loggedUser, article);
await appendFavorites(loggedUser, article);
delete article.dataValues.Favorites;
}
res
.status(200)
.json({ articles: articles.rows, articlesCount: articles.count });
});
module.exports.createArticle = asyncHandler(async (req, res, next) => {
const { loggedUser } = req;
fieldValidation(req.body.article.title, next);
fieldValidation(req.body.article.description, next);
fieldValidation(req.body.article.body, next);
const { title, description, body, tagList } = req.body.article;
const slugInDB = await Article.findOne({ where: { slug: slug(`${title}`) } });
if (slugInDB) {
return next(new ErrorResponse("Title already exists", 400));
}
const article = await Article.create({
title: title,
description: description,
body: body,
});
for (const tag of tagList) {
const tagInDB = await Tag.findByPk(tag.trim());
if (tagInDB) {
await article.addTagList(tagInDB);
} else if (tag.length > 2) {
const newTag = await Tag.create({ name: tag.trim() });
await article.addTagList(newTag);
}
}
delete loggedUser.dataValues.token;
article.dataValues.tagList = tagList;
article.setAuthor(loggedUser);
article.dataValues.author = loggedUser;
await appendFollowers(loggedUser, loggedUser);
await appendFavorites(loggedUser, article);
res.status(201).json({ article });
});
module.exports.deleteArticle = asyncHandler(async (req, res, next) => {
const { slug } = req.params;
const { loggedUser } = req;
const article = await Article.findOne({
where: { slug: slug },
include: includeOptions,
});
if (!article) {
return next(new ErrorResponse("Article not found", 404));
}
if (article.authorId !== loggedUser.id) {
return next(new ErrorResponse("Unauthorized", 401));
}
await article.destroy();
res.status(200).json({ article });
});
module.exports.updateArticle = asyncHandler(async (req, res, next) => {
const { slug } = req.params;
const { loggedUser } = req;
const article = await Article.findOne({
where: { slug: slug },
include: includeOptions,
});
if (!article) {
return next(new ErrorResponse("Article not found", 404));
}
if (article.authorId !== loggedUser.id) {
return next(new ErrorResponse("Unauthorized", 401));
}
const { title, description, body } = req.body.article;
const slugInDB = await Article.findOne({
where: {
slug: slug(title ? title : article.title)
},
});
if (slugInDB && slugInDB.slug !== slug) {
return next(new ErrorResponse("Title already exists", 400));
}
await article.update({
title: title ? title : article.title,
description: description ? description : article.description,
body: body ? body : article.body,
});
const articleTags = await article.getTagLists();
appendTagList(articleTags, article);
await appendFollowers(loggedUser, article);
await appendFavorites(loggedUser, article);
res.status(200).json({ article });
});
module.exports.articlesFeed = asyncHandler(async (req, res) => {
const { loggedUser } = req;
const { limit = 3, offset = 0 } = req.query;
const authors = await loggedUser.getFollowing();
const articles = await Article.findAndCountAll({
include: includeOptions,
limit: parseInt(limit),
offset: offset * limit,
order: [["createdAt", "DESC"]],
where: { authorId: authors.map((author) => author.id) },
distinct: true,
});
for (const article of articles.rows) {
const articleTags = await article.getTagLists();
appendTagList(articleTags, article);
await appendFollowers(loggedUser, article);
await appendFavorites(loggedUser, article);
}
res.json({ articles: articles.rows, articlesCount: articles.count });
});
module.exports.addFavoriteArticle = asyncHandler(async (req, res, next) => {
const { loggedUser } = req;
const { slug } = req.params;
const article = await Article.findOne({
where: { slug: slug },
include: includeOptions,
});
if (!article) {
return next(new ErrorResponse("Article not found", 404));
}
await loggedUser.addFavorite(article);
const articleTags = await article.getTagLists();
appendTagList(articleTags, article);
await appendFollowers(loggedUser, article);
await appendFavorites(loggedUser, article);
res.status(200).json({ article });
});
module.exports.deleteFavoriteArticle = asyncHandler(async (req, res, next) => {
const { loggedUser } = req;
const { slug } = req.params;
const article = await Article.findOne({
where: { slug: slug },
include: includeOptions,
});
if (!article) {
return next(new ErrorResponse("Article not found", 404));
}
await loggedUser.removeFavorite(article);
const articleTags = await article.getTagLists();
appendTagList(articleTags, article);
await appendFollowers(loggedUser, article);
await appendFavorites(loggedUser, article);
res.status(200).json({ article });
});
const fieldValidation = (field, next) => {
if (!field) {
return next(new ErrorResponse(`Missing fields`, 400));
}
};
const getAllArticles = async (req, res) => {
try {
const articles = await ArticleService.getAllArticles();
res.status(200).json({
data: articles,
});
} catch (err) {
res.status(500).json({
message: 'something went wrong while fetching articles',
error: err.message,
});
}
};
const getArticlesByUserId = async (req, res) => {
try {
const { authorId } = req.params;
const articles = await ArticleService.getArticlesByUserId(authorId);
res.status(200).json({
data: articles,
});
} catch (err) {
console.log(err);
res.status(500).json({
message: 'something went wrong while fetching articles',
error: err.message,
});
}
};
module.exports = { createArticle, getAllArticles, getArticlesByUserId };
+277
View File
@@ -0,0 +1,277 @@
//const { ProductService } = require('../services');
//const { where } = require("sequelize");
const asyncHandler = require("../middlewares/asyncHandler");
const Product = require("../database/models/mysql/Product");
const Tag = require("../database/models/mysql/Tag");
const User = require("../database/models/mysql/User");
const ErrorResponse = require("../utils/errorResponse");
const slug = require("slug");
const {
appendFollowers,
appendFavorites,
appendTagList,
} = require("../utils/helpers");
const includeOptions = [
{
model: Tag,
as: "tagLists",
attributes: ["name"],
through: { attributes: [] },
},
{ model: User, as: "author", attributes: { exclude: ["email", "password"] } },
];
module.exports.getProducts = asyncHandler(async (req, res) => {
const { tag, author, favorited, limit = 20, offset = 0 } = req.query;
const { loggedUser } = req;
const searchOptions = {
include: [
{
model: Tag,
as: "tagLists",
attributes: ["name"],
through: { attributes: [] }, // ? this will remove the rows from the join table
// where: tag ? { name: tag } : {},
...(tag && { where: { name: tag } }),
},
{
model: User,
as: "author",
attributes: { exclude: ["password", "email"] },
// where: author ? { username: author } : {},
...(author && { where: { username: author } }),
},
],
limit: parseInt(limit),
offset: parseInt(offset),
order: [["createdAt", "DESC"]],
distinct: true,
};
let products = { rows: [], count: 0 };
if (favorited) {
const user = await User.findOne({ where: { username: favorited } });
products.rows = await user.getFavorites(searchOptions);
products.count = await user.countFavorites();
} else {
products = await Product.findAndCountAll(searchOptions);
}
for (let product of products.rows) {
const productTags = await product.getTagLists();
// const productTags = product.tagLists;
appendTagList(productTags, product);
await appendFollowers(loggedUser, product);
await appendFavorites(loggedUser, product);
delete product.dataValues.Favorites;
}
res
.status(200)
.json({ products: products.rows, productsCount: products.count });
});
module.exports.createProduct = asyncHandler(async (req, res, next) => {
const { loggedUser } = req;
fieldValidation(req.body.product.title, next);
fieldValidation(req.body.product.description, next);
fieldValidation(req.body.product.body, next);
const { title, description, body, tagList } = req.body.product;
const slugInDB = await Product.findOne({ where: { slug: slug(`${title}`) } });
if (slugInDB) {
next(new ErrorResponse("Title already exists", 400));
}
const product = await Product.create({
title: title,
description: description,
body: body,
});
for (const tag of tagList) {
const tagInDB = await Tag.findByPk(tag.trim());
if (tagInDB) {
await product.addTagList(tagInDB);
} else if (tag.length > 2) {
const newTag = await Tag.create({ name: tag.trim() });
await product.addTagList(newTag);
}
}
delete loggedUser.dataValues.token;
product.dataValues.tagList = tagList;
product.setAuthor(loggedUser);
product.dataValues.author = loggedUser;
await appendFollowers(loggedUser, loggedUser);
await appendFavorites(loggedUser, product);
res.status(201).json({ product });
});
module.exports.deleteProduct = asyncHandler(async (req, res, next) => {
const { slug } = req.params;
const { loggedUser } = req;
const product = await Product.findOne({
where: { slug: slug },
include: includeOptions,
});
if (!product) {
next(new ErrorResponse("Product not found", 404));
}
if (product.authorId !== loggedUser.id) {
return next(new ErrorResponse("Unauthorized", 401));
}
await product.destroy();
res.status(200).json({ product });
});
module.exports.updateProduct = asyncHandler(async (req, res, next) => {
const { slug } = req.params;
const { loggedUser } = req;
const product = await Product.findOne({
where: { slug: slug },
include: includeOptions,
});
if (!product) {
next(new ErrorResponse("Product not found", 404));
}
if (product.authorId !== loggedUser.id) {
return next(new ErrorResponse("Unauthorized", 401));
}
const { title, description, body } = req.body.product;
const slugInDB = await Product.findOne({
where: { slug: slug(title ? title : product.title) },
});
if (slugInDB && slugInDB.slug !== slug) {
return next(new ErrorResponse("Title already exists", 400));
}
await product.update({
title: title ? title : product.title,
description: description ? description : product.description,
body: body ? body : product.body,
});
const productTags = await product.getTagLists();
appendTagList(productTags, product);
await appendFollowers(loggedUser, product);
await appendFavorites(loggedUser, product);
res.status(200).json({ product });
});
module.exports.productsFeed = asyncHandler(async (req, res) => {
const { loggedUser } = req;
const { limit = 3, offset = 0 } = req.query;
const authors = await loggedUser.getFollowing();
const products = await Product.findAndCountAll({
include: includeOptions,
limit: parseInt(limit),
offset: offset * limit,
order: [["createdAt", "DESC"]],
where: { authorId: authors.map((author) => author.id) },
distinct: true,
});
for (const product of products.rows) {
const productTags = await product.getTagLists();
appendTagList(productTags, product);
await appendFollowers(loggedUser, product);
await appendFavorites(loggedUser, product);
}
res.json({ products: products.rows, productsCount: products.count });
});
module.exports.getProduct = asyncHandler(async (req, res, next) => {
const { loggedUser } = req;
const { slug } = req.params;
const product = await Product.findOne({
where: { slug: slug },
include: includeOptions,
});
if (!product) {
return next(new ErrorResponse("Product not found", 404));
}
const productTags = await product.getTagLists();
appendTagList(productTags, product);
await appendFollowers(loggedUser, product);
await appendFavorites(loggedUser, product);
res.status(200).json({ product });
});
module.exports.addFavoriteProduct = asyncHandler(async (req, res, next) => {
const { loggedUser } = req;
const { slug } = req.params;
const product = await Product.findOne({
where: { slug: slug },
include: includeOptions,
});
if (!product) {
return next(new ErrorResponse("Product not found", 404));
}
await loggedUser.addFavorite(product);
const productTags = await product.getTagLists();
appendTagList(productTags, product);
await appendFollowers(loggedUser, product);
await appendFavorites(loggedUser, product);
res.status(200).json({ product });
});
module.exports.deleteFavoriteProduct = asyncHandler(async (req, res, next) => {
const { loggedUser } = req;
const { slug } = req.params;
const product = await Product.findOne({
where: { slug: slug },
include: includeOptions,
});
if (!product) {
return next(new ErrorResponse("Product not found", 404));
}
await loggedUser.removeFavorite(product);
const productTags = await product.getTagLists();
appendTagList(productTags, product);
await appendFollowers(loggedUser, product);
await appendFavorites(loggedUser, product);
res.status(200).json({ product });
});
const fieldValidation = (field, next) => {
if (!field) {
return next(new ErrorResponse(`Missing fields`, 400));
}
};
+87 -5
View File
@@ -2,11 +2,35 @@
const { UserService } = require('../services');
const passport = require('passport');
const authenticate = async (req, res, next) => {
try {
passport.authenticate('headerapikey', { session: false }, function (err, application, info) {
if (err) {
return res.status(err.status || 500).json({message: "An authentication error occured.", err: err.message});
//return next(err);
}
if (!application) {
return res.status(401).json({message: "Unauthorized - You are not allowed to access this resource.", err: err, info: info});
}
if (application.author) {
application.author.token = application.author.generateJWT();
return res.json({ user: application.author.toAuthJSON(), application: application.toAuthJSON() });
} else {
return res.status(422).json(info);
}
})(req, res, next);
} catch (err) {
res.status(500).json({
message: 'something went wrong while creating user',
error: err.message,
});
}
};
const createUser = async (req, res) => {
try {
const { name, email } = req.body;
const user = await UserService.createUser({ name, email });
const { username, firstname, lastname, email } = req.body.user;
const user = await UserService.createUser({ username, firstname, lastname, email });
res.status(201).json({
message: 'User created successfully',
@@ -38,6 +62,9 @@ const getAllUsers = async (req, res) => {
const getUser = async (req, res) => {
try {
const user = await UserService.getUserById(req.payload.id);
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
res.status(200).json({
user: user.toAuthJSON(),
@@ -71,10 +98,65 @@ const loginAsUser = async (req, res, next) => {
})(req, res, next);
} catch (err) {
res.status(500).json({
message: 'something went wrong while fetching users',
message: 'something went wrong while processing login',
error: err.message,
});
}
};
module.exports = { createUser, getAllUsers, getUser, loginAsUser };
const updateUser = async (req, res) => {
try {
let user = await UserService.getUserById(req.payload.id);
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
if (typeof req.body.user.username !== 'undefined') {
user.username = req.body.user.username;
}
if (typeof req.body.user.email !== 'undefined') {
user.email = req.body.user.email;
}
if (typeof req.body.user.firstname !== 'undefined') {
user.firstname = req.body.user.firstname;
}
if (typeof req.body.user.lastname !== 'undefined') {
user.lastname = req.body.user.lastname;
}
if (typeof req.body.user.phone !== 'undefined') {
user.phone = req.body.user.phone;
}
if (typeof req.body.user.licence !== 'undefined') {
user.licence = req.body.user.licence;
}
if (typeof req.body.user.poids !== 'undefined') {
user.poids = req.body.user.poids;
}
if (typeof req.body.user.image !== 'undefined') {
user.image = req.body.user.image;
}
if (typeof req.body.user.bg_image !== 'undefined') {
user.bg_image = req.body.user.bg_image;
}
if (typeof req.body.user.password !== 'undefined') {
user.setPassword(req.body.user.password);
}
if (typeof req.body.user.role !== 'undefined') {
user.role = req.body.user.role;
}
/*user = await UserService.updateUser(req.body.user);
res.status(200).json({
user: user.toAuthJSON(),
});*/
return user.save().then(function () {
return res.json({ user: user.toAuthJSON() });
});
} catch (err) {
res.status(500).json({
message: 'something went wrong while updating user',
error: err.message,
});
}
};
module.exports = { authenticate, createUser, getAllUsers, getUser, loginAsUser, updateUser };