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 <yidhra@tuta.io>
This commit is contained in:
parent
4a9bc402b4
commit
23116f4345
41
src/controllers/category.controller.ts
Normal file
41
src/controllers/category.controller.ts
Normal file
@ -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<Response>} The response object indicating the outcome of the category creation.
|
||||||
|
*/
|
||||||
|
async function createCategory(req: Request, res: Response): Promise<Response> {
|
||||||
|
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;
|
Loading…
x
Reference in New Issue
Block a user