noteController.ts63 lines, 1.8 KB
| 1 | import { Request, Response } from "express"; |
| 2 | import { asyncHandler } from "../../../shared/middleware"; |
| 3 | import { NotesService } from "./notesService"; |
| 4 | import { |
| 5 | createErrorResponse, |
| 6 | createSuccessResponse, |
| 7 | parseEnvInt, |
| 8 | } from "../../../shared/utils"; |
| 9 | |
| 10 | const noteService = new NotesService(); |
| 11 | |
| 12 | export const createNote = asyncHandler(async (req: Request, res: Response) => { |
| 13 | const userId = req.user?.userId; |
| 14 | |
| 15 | if (!userId) { |
| 16 | return res.status(401).json(createErrorResponse("Unauthorized")); |
| 17 | } |
| 18 | |
| 19 | // Extract JWT token from auth he |
| 20 | const authHeader = req.headers.authorization; |
| 21 | const authToken = authHeader?.startsWith("Bearer ") |
| 22 | ? authHeader.slice(7) |
| 23 | : undefined; |
| 24 | |
| 25 | const note = await noteService.createNote(userId, req.body, authToken); |
| 26 | |
| 27 | return res |
| 28 | .status(201) |
| 29 | .json(createSuccessResponse(note, "Note created successfully")); |
| 30 | }); |
| 31 | |
| 32 | export const getNotes = asyncHandler(async (req: Request, res: Response) => { |
| 33 | const userId = req.user?.userId; |
| 34 | |
| 35 | if (!userId) { |
| 36 | return res.status(401).json(createErrorResponse("Unauthorized")); |
| 37 | } |
| 38 | |
| 39 | const page = parseEnvInt(req.query.page as string, 1); |
| 40 | const limit = parseEnvInt(req.query.limit as string, 50); |
| 41 | const search = req.query.search as string; |
| 42 | |
| 43 | const result = await noteService.getNotesByUser(userId, page, limit, search); |
| 44 | |
| 45 | return res |
| 46 | .status(200) |
| 47 | .json(createSuccessResponse(result, "Notes retrieved successfully")); |
| 48 | }); |
| 49 | |
| 50 | export const getNoteById = asyncHandler(async (req: Request, res: Response) => { |
| 51 | const userId = req.user?.userId; |
| 52 | const { noteId } = req.params; |
| 53 | |
| 54 | if (!userId) { |
| 55 | return res.status(401).json(createErrorResponse("Unauthorized")); |
| 56 | } |
| 57 | |
| 58 | const note = await noteService.getNoteById(noteId, userId); |
| 59 | |
| 60 | return res |
| 61 | .status(200) |
| 62 | .json(createSuccessResponse(note, "Note retrieved successfully")); |
| 63 | }); |