question.controller.ts 2.04 KB
Newer Older
Jiwon Yoon's avatar
Jiwon Yoon committed
1
import { NextFunction, Request, Response } from "express";
Jiwon Yoon's avatar
Jiwon Yoon committed
2
import { questionDb, surveyDb } from "../db";
Jiwon Yoon's avatar
Jiwon Yoon committed
3
4
import { asyncWrap } from "../helpers/asyncWrap";

Jiwon Yoon's avatar
Jiwon Yoon committed
5
6
7
8
9
10
11
export interface TypedRequestAuth<T> extends Request {
  auth: T;
  user: any;
}

export const createQuestion = asyncWrap(
  async (reqExp: Request, res: Response, next: NextFunction) => {
Jiwon Yoon's avatar
Jiwon Yoon committed
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
    try {
      const req = reqExp as TypedRequestAuth<{ userId: string }>;
      const { userId } = req.auth;
      if (!userId) {
        return res.status(404).send("올바른 접근이 아닙니다");
      } else {
        let question = req.body;
        question.user = userId;
        const newQuestion = await questionDb.createQuestion(question);
        const { surveyId } = req.params;
        const updatedSurvey = await surveyDb.putNewQuestion(
          newQuestion,
          surveyId
        );
        console.log(updatedSurvey);
Yoon, Daeki's avatar
Yoon, Daeki committed
27
28
        // return res.json(updatedSurvey?.questions);
        return res.json(newQuestion);
Jiwon Yoon's avatar
Jiwon Yoon committed
29
30
      }
    } catch (error: any) {
Yoon, Daeki's avatar
Yoon, Daeki committed
31
      return res.status(500).send(error.message || "질문 생성 오류");
Jiwon Yoon's avatar
Jiwon Yoon committed
32
    }
Jiwon Yoon's avatar
Jiwon Yoon committed
33
34
  }
);
Jiwon Yoon's avatar
Jiwon Yoon committed
35
36
37
38
39
40
41

export const updateQuestion = asyncWrap(async (req, res) => {
  const question = req.body;
  const newQuestion = await questionDb.updateQuestion(question);
  return res.json(newQuestion);
});

Jiwon Yoon's avatar
Jiwon Yoon committed
42
43
44
export const deleteQuestionById = asyncWrap(async (req, res) => {
  const { questionId } = req.params;
  const newQuestion = await questionDb.deleteQuestionById(questionId);
Jiwon Yoon's avatar
Jiwon Yoon committed
45
46
  return res.json(newQuestion);
});
Jiwon Yoon's avatar
Jiwon Yoon committed
47
48
49
50
51
52
53
54
55
56
57

export const userByQuestionId = async (
  reqExp: Request,
  res: Response,
  next: NextFunction,
  questionId: string
) => {
  try {
    const req = reqExp as TypedRequestAuth<{ userId: string }>;
    let user = await questionDb.findUserByQuestionId(questionId);
    if (!user) {
58
59
60
61
      return res.status(404).send("올바른 접근이 아닙니다");
    } else {
      req.user = user;
      next();
Jiwon Yoon's avatar
Jiwon Yoon committed
62
63
64
65
66
67
68
    }
  } catch (error: any) {
    return res
      .status(500)
      .send(error.message || "질문을 작성한 사용자를 찾아내는 중 오류 발생");
  }
};