|
| 1 | +import express from "express"; |
| 2 | +import { QuestionDao } from "../models/questions"; |
| 3 | +import { ApiResponse, EMPTY_OBJECT, StatusMessageType } from "../types"; |
| 4 | + |
| 5 | +// GET /questions/:id |
| 6 | +export const getQuestion = async ( |
| 7 | + req: express.Request, |
| 8 | + res: express.Response |
| 9 | +) => { |
| 10 | + try { |
| 11 | + const id = req.params.id; |
| 12 | + if (!id) { |
| 13 | + const response: ApiResponse = { |
| 14 | + payload: EMPTY_OBJECT, |
| 15 | + statusMessage: { |
| 16 | + type: StatusMessageType.ERROR, |
| 17 | + message: "No ID provided", |
| 18 | + }, |
| 19 | + }; |
| 20 | + |
| 21 | + res.status(400).json(response); |
| 22 | + } |
| 23 | + |
| 24 | + const question = await QuestionDao.getQuestionById(id); |
| 25 | + if (!question) { |
| 26 | + const response: ApiResponse = { |
| 27 | + payload: EMPTY_OBJECT, |
| 28 | + statusMessage: { |
| 29 | + type: StatusMessageType.ERROR, |
| 30 | + message: "No question found", |
| 31 | + }, |
| 32 | + }; |
| 33 | + |
| 34 | + res.status(404).json(response); |
| 35 | + } |
| 36 | + |
| 37 | + const response: ApiResponse = { |
| 38 | + payload: question, |
| 39 | + statusMessage: null, |
| 40 | + }; |
| 41 | + res.status(200).json(response); |
| 42 | + } catch (error) { |
| 43 | + console.log(error); |
| 44 | + const response: ApiResponse = { |
| 45 | + payload: EMPTY_OBJECT, |
| 46 | + statusMessage: { |
| 47 | + type: StatusMessageType.ERROR, |
| 48 | + message: "Something went wrong", |
| 49 | + }, |
| 50 | + }; |
| 51 | + |
| 52 | + res.status(500).json(response); |
| 53 | + } |
| 54 | +}; |
| 55 | + |
| 56 | +// POST /questions |
| 57 | +export const createQuestion = async ( |
| 58 | + req: express.Request, |
| 59 | + res: express.Response |
| 60 | +) => { |
| 61 | + try { |
| 62 | + const { title, description } = req.body; |
| 63 | + if (!title || !description) { |
| 64 | + const response: ApiResponse = { |
| 65 | + payload: EMPTY_OBJECT, |
| 66 | + statusMessage: { |
| 67 | + type: StatusMessageType.ERROR, |
| 68 | + message: "Title or description must provided", |
| 69 | + }, |
| 70 | + }; |
| 71 | + |
| 72 | + res.status(400).json(response); |
| 73 | + } |
| 74 | + |
| 75 | + const question = await QuestionDao.createQuestion(title, description); |
| 76 | + const response: ApiResponse = { |
| 77 | + payload: question, |
| 78 | + statusMessage: null, |
| 79 | + }; |
| 80 | + res.status(201).json(response); |
| 81 | + } catch (error) { |
| 82 | + console.log(error); |
| 83 | + const response: ApiResponse = { |
| 84 | + payload: EMPTY_OBJECT, |
| 85 | + statusMessage: { |
| 86 | + type: StatusMessageType.ERROR, |
| 87 | + message: "Something went wrong", |
| 88 | + }, |
| 89 | + }; |
| 90 | + |
| 91 | + res.status(500).json(response); |
| 92 | + } |
| 93 | +}; |
0 commit comments