survey.controller.ts 1.69 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 { surveyDb } 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
21
22
23
24
25
26
27
28
export interface TypedRequestAuth<T> extends Request {
  auth: T;
  user: any;
}

export const createSurvey = asyncWrap(
  async (reqExp: Request, res: Response, next: NextFunction) => {
    const req = reqExp as TypedRequestAuth<{ userId: string }>;
    const { userId } = req.auth;
    let survey = req.body;
    survey.user = userId;
    console.log("survey body", survey);
    const newSurvey = await surveyDb.createSurvey(survey);
    return res.json(newSurvey);
  }
);

export const getSurveyById = asyncWrap(async (req, res) => {
  const { surveyId } = req.params;
  const survey = await surveyDb.getSurveyById(surveyId);
  console.log("Get완료", survey);
  return res.json(survey);
});

29
30
31
32
33
34
//동혁
export const getSurveys = asyncWrap(async(req,res)=>{
  const surveys = await surveyDb.getSurveys();
  return res.json(surveys);
});

Jiwon Yoon's avatar
Jiwon Yoon committed
35
export const updateSurvey = asyncWrap(async (req, res) => {
Jiwon Yoon's avatar
Jiwon Yoon committed
36
  const survey = req.body;
Jiwon Yoon's avatar
Jiwon Yoon committed
37
  const newSurvey = await surveyDb.updateSurvey(survey);
Jiwon Yoon's avatar
Jiwon Yoon committed
38
39
  return res.json(newSurvey);
});
Jiwon Yoon's avatar
Jiwon Yoon committed
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62

export const userBySurveyId = async (
  reqExp: Request,
  res: Response,
  next: NextFunction,
  surveyId: string
) => {
  try {
    const req = reqExp as TypedRequestAuth<{ userId: string }>;
    let user = await surveyDb.findUserBySurveyId(surveyId);
    if (!user) {
      return res.status(404).send("사용자를 찾을 수 없습니다");
    }
    req.user = user;
    next();
  } catch (error: any) {
    return res
      .status(500)
      .send(
        error.message || "설문조사를 작성한 사용자를 찾아내는 중 오류 발생"
      );
  }
};