Refactoring et ajout de routes Hero Wars

This commit is contained in:
2025-11-27 10:50:17 +01:00
parent c9ce3f343e
commit 60feffd929
47 changed files with 1224 additions and 236 deletions
+81 -68
View File
@@ -1,22 +1,23 @@
const { ArticleService } = require('../services');
//const { where } = require("sequelize");
const asyncHandler = require("../middlewares/asyncHandler");
const Article = require("../database/models/mysql/Article");
/*const Article = require("../database/models/mysql/Article");
const Tag = require("../database/models/mysql/Tag");
const User = require("../database/models/mysql/User");
const User = require("../database/models/mysql/User");*/
const ErrorResponse = require("../utils/errorResponse");
const slug = require("slug");
const {
const DB = require('../database/mysql');
const { Article, Tag, User } = DB;
/*const {
appendFollowers,
appendFavorites,
appendTagList,
} = require("../utils/helpers");
} = require("../utils/helpers");*/
const includeOptions = [
{
model: Tag,
as: "tagLists",
as: "articleTags",
attributes: ["name"],
through: { attributes: [] },
},
@@ -31,7 +32,7 @@ module.exports.getArticle = asyncHandler(async (req, res, next) => {
if (!article) {
return next(new ErrorResponse("Article not found", 404));
}
let tagList = article.tagNameTagTagLists;
let tagList = article.articleTags;
//let author = article.author;
article = article.toJSONFor();
article.tagList = tagList;
@@ -40,58 +41,70 @@ module.exports.getArticle = asyncHandler(async (req, res, next) => {
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;
module.exports.getArticles = asyncHandler(async (req, res, next) => {
try {
const { tag, author, favorited, limit = 20, offset = 0 } = req.query;
//const { loggedUser } = req;
const loggedUser = await User.findOne({
attributes: { exclude: ["password", "email", "hash", "salt"] },
where: { id: req.payload.id },
});
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,
};
const searchOptions = {
include: [
{
model: Tag,
as: "articleTags",
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", "hash", "salt"] },
// where: author ? { username: author } : {},
...(author && { where: { username: author } }),
},
],
limit: parseInt(limit),
offset: parseInt(offset),
order: [["createdAt", "DESC"]],
distinct: true,
};
let articles = { rows: [], count: 0 };
let articles = { rows: [], count: 0 };
if (favorited) {
const user = await User.findOne({ where: { username: favorited } });
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);
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();
//console.log("articleTags: ", articleTags);
// const articleTags = article.tagLists;
ArticleService.appendTagList(articleTags, article);
await ArticleService.appendFollowers(loggedUser, article);
await ArticleService.appendFavorites(loggedUser, article);
//delete article.dataValues.Favorites;
}
res.status(200).json({
data: {
articles: articles.rows,
articlesCount: articles.count
}
});
} catch (err) {
return next(new ErrorResponse(`Something went wrong while fetching articles - ${err.message}`, 500));
}
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) => {
@@ -128,8 +141,8 @@ module.exports.createArticle = asyncHandler(async (req, res, next) => {
article.dataValues.tagList = tagList;
article.setAuthor(loggedUser);
article.dataValues.author = loggedUser;
await appendFollowers(loggedUser, loggedUser);
await appendFavorites(loggedUser, article);
await ArticleService.appendFollowers(loggedUser, loggedUser);
await ArticleService.appendFavorites(loggedUser, article);
res.status(201).json({ article });
});
@@ -192,9 +205,9 @@ module.exports.updateArticle = asyncHandler(async (req, res, next) => {
});
const articleTags = await article.getTagLists();
appendTagList(articleTags, article);
await appendFollowers(loggedUser, article);
await appendFavorites(loggedUser, article);
ArticleService.appendTagList(articleTags, article);
await ArticleService.appendFollowers(loggedUser, article);
await ArticleService.appendFavorites(loggedUser, article);
res.status(200).json({ article });
});
@@ -217,9 +230,9 @@ module.exports.articlesFeed = asyncHandler(async (req, res) => {
for (const article of articles.rows) {
const articleTags = await article.getTagLists();
appendTagList(articleTags, article);
await appendFollowers(loggedUser, article);
await appendFavorites(loggedUser, article);
ArticleService.appendTagList(articleTags, article);
await ArticleService.appendFollowers(loggedUser, article);
await ArticleService.appendFavorites(loggedUser, article);
}
res.json({ articles: articles.rows, articlesCount: articles.count });
@@ -241,9 +254,9 @@ module.exports.addFavoriteArticle = asyncHandler(async (req, res, next) => {
await loggedUser.addFavorite(article);
const articleTags = await article.getTagLists();
appendTagList(articleTags, article);
await appendFollowers(loggedUser, article);
await appendFavorites(loggedUser, article);
ArticleService.appendTagList(articleTags, article);
await ArticleService.appendFollowers(loggedUser, article);
await ArticleService.appendFavorites(loggedUser, article);
res.status(200).json({ article });
});
@@ -264,9 +277,9 @@ module.exports.deleteFavoriteArticle = asyncHandler(async (req, res, next) => {
await loggedUser.removeFavorite(article);
const articleTags = await article.getTagLists();
appendTagList(articleTags, article);
await appendFollowers(loggedUser, article);
await appendFavorites(loggedUser, article);
ArticleService.appendTagList(articleTags, article);
await ArticleService.appendFollowers(loggedUser, article);
await ArticleService.appendFavorites(loggedUser, article);
res.status(200).json({ article });
});
+139
View File
@@ -0,0 +1,139 @@
const { HWClanService } = require('../services');
const asyncHandler = require("../middlewares/asyncHandler");
const ErrorResponse = require("../utils/errorResponse");
var mongoose = require('mongoose'),
User = mongoose.model('User');
module.exports.createClan = asyncHandler(async (req, res, next) => {
try {
const {
id, title, country, description, disbanding, frameId, icon, level, members,
membersCount, minLevel, ownerId, serverId, topActivity, topDungeon
} = req.body;
const author = await User.findById(req.payload.id).then(function (user) {
return user._id;
});
const clan = await HWClanService.createClan({
id, title, country, description, disbanding, frameId, icon, level, members,
membersCount, minLevel, ownerId, serverId, topActivity, topDungeon, author
});
//console.log(clan);
res.status(201).json({
message: 'Clan created successfully',
data: clan.toJSONFor(),
});
} catch (err) {
return next(new ErrorResponse(`Something went wrong while creating clan - ${err.message}`, 500));
}
});
module.exports.getAllClans = asyncHandler(async (req, res, next) => {
try {
let query = {};
let { limit = 25, offset = 0 } = req.query;
if (typeof req.query.title !== 'undefined') {
const rgx = new RegExp(`.*${req.query.title}.*`);
query = {
$or: [
{ title: { $regex: rgx, $options: "i" } },
{ id: { $regex: rgx, $options: "i" } },
],
}
}
const data = await HWClanService.getAllClans(query, limit, offset);
res.status(200).json({
data: {
clans: data.clans.map(function (clan) {
return clan.toJSONFor();
}),
clansCount: data.clansCount
}
});
} catch (err) {
return next(new ErrorResponse(`Something went wrong while fetching clans - ${err.message}`, 500));
}
});
module.exports.getClan = asyncHandler(async (req, res, next) => {
try {
//console.log("Clan controller getClan");
const { clanId } = req.params;
let clan = await HWClanService.getClanById(clanId);
if (!clan) {
return next(new ErrorResponse("Clan not found", 404));
}
res.status(200).json({ clan: clan.toJSONFor() });
} catch (err) {
return next(new ErrorResponse(`Something went wrong while fetching clan - ${err.message}`, 500));
}
});
module.exports.updateClan = asyncHandler(async (req, res, next) => {
try {
//console.log("Clan controller updateClan", req.payload);
const { clanId } = req.params;
let clan = await HWClanService.getClanById(clanId);
//console.log(req.body.clan, clan);
if (req.payload.id !== clan.author._id.toString()) {
return next(new ErrorResponse("Unauthorized", 401));
}
Object.assign(clan, req.body.clan);
let data = await HWClanService.updateClan(clan);
//res.status(200).json({ clan: data.toJSONFor() });
res.status(200).json({
message: 'Clan updated successfully',
clan: data.toJSONFor()
});
} catch (err) {
return next(new ErrorResponse(`Something went wrong while updating clan - ${err.message}`, 500));
}
});
module.exports.deleteClan = asyncHandler(async (req, res, next) => {
try {
const { clanId } = req.params;
let clan = await HWClanService.getClanById(clanId);
//console.log(clanId, clan.author._id.toString(), req.payload.id);
if (req.payload.id !== clan.author._id.toString()) {
return next(new ErrorResponse("Unauthorized", 401));
}
let data = await HWClanService.deleteClan(clan);
res.status(200).json({
message: 'Clan deleted successfully',
data: data.id
});
} catch (err) {
return next(new ErrorResponse(`Something went wrong while deleting clan - ${err.message}`, 500));
}
});
/*
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 });
});
*/
+110
View File
@@ -0,0 +1,110 @@
const { HWMemberService } = require('../services');
const asyncHandler = require("../middlewares/asyncHandler");
const ErrorResponse = require("../utils/errorResponse");
var mongoose = require('mongoose'),
User = mongoose.model('User');
module.exports.createMember = asyncHandler(async (req, res, next) => {
try {
const {
id, allowPm, avatarId, clanIcon, clanId, clanRole, clanTitle, commander, frameId,
isChatModerator, lastLoginTime, leagueId, level, name, serverId
} = req.body;
const author = await User.findById(req.payload.id).then(function (user) {
return user._id;
});
const member = await HWMemberService.createMember({
id, allowPm, avatarId, clanIcon, clanId, clanRole, clanTitle, commander, frameId,
isChatModerator, lastLoginTime, leagueId, level, name, serverId, author
});
res.status(201).json({
message: 'Member created successfully',
data: member.toJSONFor(),
});
} catch (err) {
return next(new ErrorResponse(`Something went wrong while creating member - ${err.message}`, 500));
}
});
module.exports.getAllMembers = asyncHandler(async (req, res, next) => {
try {
let query = {};
let { limit = 25, offset = 0 } = req.query;
if (typeof req.query.name !== 'undefined') {
const rgx = new RegExp(`.*${req.query.name}.*`);
query = {
$or: [
{ name: { $regex: rgx, $options: "i" } },
{ id: { $regex: rgx, $options: "i" } },
],
}
}
const data = await HWMemberService.getAllMembers(query, limit, offset);
res.status(200).json({
data: {
members: data.members.map(function (member) {
return member.toJSONFor();
}),
membersCount: data.membersCount
}
});
} catch (err) {
return next(new ErrorResponse(`Something went wrong while fetching members - ${err.message}`, 500));
}
});
module.exports.getMember = asyncHandler(async (req, res, next) => {
try {
const { memberId } = req.params;
let member = await HWMemberService.getMemberById(memberId);
if (!member) {
return next(new ErrorResponse("Member not found", 404));
}
res.status(200).json({ member: member.toJSONFor() });
} catch (err) {
return next(new ErrorResponse(`Something went wrong while updating member - ${err.message}`, 500));
}
});
module.exports.updateMember = asyncHandler(async (req, res, next) => {
try {
const { memberId } = req.params;
let member = await HWMemberService.getMemberById(memberId);
if (req.payload.id !== member.author._id.toString()) {
return next(new ErrorResponse("Unauthorized", 401));
}
Object.assign(member, req.body.member);
let data = await HWMemberService.updateMember(member);
res.status(200).json({
message: 'Member updated successfully',
member: data.toJSONFor()
});
} catch (err) {
return next(new ErrorResponse(`Something went wrong while updating member - ${err.message}`, 500));
}
});
module.exports.deleteMember = asyncHandler(async (req, res, next) => {
try {
const { memberId } = req.params;
let member = await HWMemberService.getMemberById(memberId);
if (req.payload.id !== member.author._id.toString()) {
return next(new ErrorResponse("Unauthorized", 401));
}
let data = await HWMemberService.deleteMember(member);
res.status(200).json({
message: 'Member deleted successfully',
data: data.id
});
} catch (err) {
return next(new ErrorResponse(`Something went wrong while deleting member - ${err.message}`, 500));
}
});
+36 -47
View File
@@ -1,4 +1,4 @@
//const { ProductService } = require('../services');
const { ProductService } = require('../services');
//const { where } = require("sequelize");
const asyncHandler = require("../middlewares/asyncHandler");
const Product = require("../database/models/mysql/Product");
@@ -23,6 +23,41 @@ const includeOptions = [
{ model: User, as: "author", attributes: { exclude: ["email", "password"] } },
];
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 });
*/
const { slug } = req.params;
let product = await ProductService.getProductBySlug(slug);
if (!product) {
return next(new ErrorResponse("Product not found", 404));
}
let tags = product.productTags;
product = product.toJSONFor();
product.tags = tags;
res.status(200).json({ product: product });
});
module.exports.getProducts = asyncHandler(async (req, res) => {
const { tag, author, favorited, limit = 20, offset = 0 } = req.query;
const { loggedUser } = req;
@@ -177,52 +212,6 @@ module.exports.updateProduct = asyncHandler(async (req, res, next) => {
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;
+116
View File
@@ -0,0 +1,116 @@
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 {
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.getProductsByCategory = asyncHandler(async (req, res, next) => {
const { category } = req.params;
//console.log(category);
let products = await ProductService.getProductsByCategory(category);
//console.log(products);
if (!products) {
return next(new ErrorResponse("Products not found", 404));
}
res.status(200).json({ category: category, count: products.count, products: products.rows });
});
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 });
});