question.controller.ts 1.57 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
3
4
import { questionDb } from "../db";
import { asyncWrap } from "../helpers/asyncWrap";

Jiwon Yoon's avatar
Jiwon Yoon committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
export interface TypedRequestAuth<T> extends Request {
  auth: T;
  user: any;
}

export const createQuestion = asyncWrap(
  async (reqExp: Request, res: Response, next: NextFunction) => {
    const req = reqExp as TypedRequestAuth<{ userId: string }>;
    const { userId } = req.auth;
    let question = req.body;
    question.user = userId;
    console.log("question body", question);
    const newQuestion = await questionDb.createQuestion(question);
    return res.json(newQuestion);
  }
);
Jiwon Yoon's avatar
Jiwon Yoon committed
21
22
23
24
25
26
27

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
28
29
30
export const deleteQuestionById = asyncWrap(async (req, res) => {
  const { questionId } = req.params;
  const newQuestion = await questionDb.deleteQuestionById(questionId);
Jiwon Yoon's avatar
Jiwon Yoon committed
31
32
  return res.json(newQuestion);
});
Jiwon Yoon's avatar
Jiwon Yoon committed
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53

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) {
      return res.status(404).send("사용자를 찾을 수 없습니다");
    }
    req.user = user;
    next();
  } catch (error: any) {
    return res
      .status(500)
      .send(error.message || "질문을 작성한 사용자를 찾아내는 중 오류 발생");
  }
};