feat(controllers): add update category functionality in category controller

This commit includes the creation of an updateCategory function in the category controller which allows for existing categories to be updated. It also includes appropriate error handling and response messages. In addition, it also introduces logging for the successful creation of a category.

Issue: #12
Signed-off-by: Mathis <yidhra@tuta.io>
This commit is contained in:
Mathis H (Avnyr) 2024-04-25 14:42:42 +02:00
parent 36ad90eda6
commit 56a1722412
Signed by: Mathis
GPG Key ID: DD9E0666A747D126

View File

@ -1,7 +1,8 @@
import type {Request, Response} from "express";
import {Logger} from "tslog";
import type IDbCategory from "@interfaces/database/IDbCategory";
import type IDbCategory, {IDbCategory} from "@interfaces/database/IDbCategory";
import CategoryService from "@services/category.service";
import {body} from "express-validator";
//import {validationResult} from "express-validator";
@ -30,12 +31,46 @@ async function createCategory(req: Request, res: Response): Promise<Response> {
logger.error("Failed to create category");
return res.status(500).json({ error: "Failed to create category" });
}
logger.info(`Category created successfully ! (${body.slug_name})`)
return res.status(201).json({ message: "Category created successfully" });
}
/**
* Update a category in the database.
*
* @param {Request} req - The request object containing the new category data in the request body.
* @param {Response} res - The response object used to send the result of the update operation.
*
* @return {Promise<Response>} - A promise that will be resolved with the result of the update operation.
*/
async function updateCategory(req: Request, res:Response): Promise<Response> {
const body: IDbCategory = req.body;
const categoryId = req.params["categorySlug"];
if (!categoryId) {
logger.error("Category slug is missing");
return res.status(400).json({ error: "Category slug is missing" });
}
const doesExist = await CategoryService.getById(`${categoryId}`)
if (!doesExist || !doesExist.id) {
logger.error("Category not found");
return res.status(404).json({ error: "Category not found" });
}
const updateResult = await CategoryService.update({
id: doesExist.id,
slug_name: `${body.slug_name}`,
display_name: `${body.display_name}`
})
if (!updateResult) {
logger.error("Failed to update category");
return res.status(500).json({ error: "Failed to update category" });
}
logger.info(`Category updated successfully! (${categoryId})`);
return res.status(200).json({ message: "Category updated successfully" });
}
const CategoryController = {
create: createCategory
create: createCategory,
update: updateCategory,
}
export default CategoryController;