From 23116f4345a96357250d0c35a05407cf3b7e3062 Mon Sep 17 00:00:00 2001 From: Mathis Date: Thu, 25 Apr 2024 14:21:24 +0200 Subject: [PATCH] feat(controllers): add category creation functionality A new controller, category.controller.ts, has been added to handle category creation. This includes validation to prevent the creation of duplicate categories and error handling in the event of failure to create a new category. Issue: #12 Signed-off-by: Mathis --- src/controllers/category.controller.ts | 41 ++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/controllers/category.controller.ts diff --git a/src/controllers/category.controller.ts b/src/controllers/category.controller.ts new file mode 100644 index 0000000..e73ff43 --- /dev/null +++ b/src/controllers/category.controller.ts @@ -0,0 +1,41 @@ +import type {Request, Response} from "express"; +import {Logger} from "tslog"; +import type IDbCategory from "@interfaces/database/IDbCategory"; +import CategoryService from "@services/category.service"; +//import {validationResult} from "express-validator"; + + +const logger = new Logger({ name: "CategoryController" }); + + +/** + * Creates a new category. + * + * @param {Request} req - The request object containing the category information. + * @param {Response} res - The response object to send back to the client. + * @returns {Promise} The response object indicating the outcome of the category creation. + */ +async function createCategory(req: Request, res: Response): Promise { + const body: IDbCategory = req.body + const doesExist = await CategoryService.getBySlug(`${body.slug_name}`) + if (doesExist) { + logger.error("Category already exists"); + return res.status(400).json({ error: "Category already exists" }); + } + const createResult = await CategoryService.create({ + display_name: `${body.display_name}`, + slug_name: `${body.slug_name}` + }) + if (!createResult) { + logger.error("Failed to create category"); + return res.status(500).json({ error: "Failed to create category" }); + } + return res.status(201).json({ message: "Category created successfully" }); + +} + +const CategoryController = { + create: createCategory +} + +export default CategoryController; \ No newline at end of file