tagsController.ts85 lines, 2.2 KB
| 1 | import { Request, Response } from "express"; |
| 2 | import { asyncHandler } from "../../../shared/middleware"; |
| 3 | import { TagsService } from "./tagsService"; |
| 4 | import { |
| 5 | createErrorResponse, |
| 6 | createSuccessResponse, |
| 7 | } from "../../../shared/utils"; |
| 8 | |
| 9 | const tagsService = new TagsService(); |
| 10 | |
| 11 | export const createTag = asyncHandler(async (req: Request, res: Response) => { |
| 12 | const userId = req.user?.userId; |
| 13 | |
| 14 | if (!userId) { |
| 15 | return res.status(401).json(createErrorResponse("Unauthorized")); |
| 16 | } |
| 17 | |
| 18 | const tag = await tagsService.createTag(userId, req.body); |
| 19 | |
| 20 | return res |
| 21 | .status(201) |
| 22 | .json(createSuccessResponse(tag, "Tag created successfully")); |
| 23 | }); |
| 24 | |
| 25 | export const getTags = asyncHandler(async (req: Request, res: Response) => { |
| 26 | const userId = req.user?.userId; |
| 27 | |
| 28 | if (!userId) { |
| 29 | return res.status(401).json(createErrorResponse("Unauthorized")); |
| 30 | } |
| 31 | |
| 32 | const page = parseInt(req.query.page as string) || 1; |
| 33 | const limit = Math.min(parseInt(req.query.limit as string) || 50, 100); |
| 34 | const search = req.query.search as string; |
| 35 | |
| 36 | const result = await tagsService.getTagsByUser(page, limit, search, userId); |
| 37 | |
| 38 | return res.status(200).json( |
| 39 | createSuccessResponse( |
| 40 | { |
| 41 | tags: result.tags, |
| 42 | pagination: { |
| 43 | page: result.page, |
| 44 | limit, |
| 45 | total: result.total, |
| 46 | totalPages: result.totalPages, |
| 47 | }, |
| 48 | }, |
| 49 | "Tags retrieved successfully" |
| 50 | ) |
| 51 | ); |
| 52 | }); |
| 53 | |
| 54 | export const getTagById = asyncHandler(async (req: Request, res: Response) => { |
| 55 | const userId = req.user?.userId; |
| 56 | const { tagId } = req.params; |
| 57 | |
| 58 | if (!userId) { |
| 59 | return res.status(401).json(createErrorResponse("Unauthorized")); |
| 60 | } |
| 61 | |
| 62 | const tag = await tagsService.getTagById(tagId, userId); |
| 63 | |
| 64 | return res |
| 65 | .status(200) |
| 66 | .json(createSuccessResponse(tag, "Tag retrieved successfully")); |
| 67 | }); |
| 68 | |
| 69 | export const validateTags = asyncHandler( |
| 70 | async (req: Request, res: Response) => { |
| 71 | const userId = req.user?.userId; |
| 72 | |
| 73 | if (!userId) { |
| 74 | return res.status(401).json(createErrorResponse("Unauthorized")); |
| 75 | } |
| 76 | |
| 77 | const { tagIds } = req.body; |
| 78 | |
| 79 | const result = await tagsService.validateTags(tagIds, userId); |
| 80 | |
| 81 | return res |
| 82 | .status(200) |
| 83 | .json(createSuccessResponse(result, "Tags validated successfully")); |
| 84 | } |
| 85 | ); |