answer.controller.ts 3.78 KB
Newer Older
Jiwon Yoon's avatar
Jiwon Yoon committed
1
import { NextFunction, Request, Response } from "express";
2
3
import { asyncWrap, formidableFilesToArray, isEmpty } from "../helpers";
import type { TypedRequest } from "../types";
4
import formidable from "formidable";
5
import { FileInfo, IAnswer } from "../models";
Jiwon Yoon's avatar
Jiwon Yoon committed
6
import { fileDb, userDb, answerDb, surveyDb } from "../db";
7
8
9
10
11
import fs from "fs/promises";

export const createAnswers = asyncWrap(async (reqExp, res) => {
  const req = reqExp as TypedRequest;
  const answer = req.body;
12
  console.log("answer in create answers:", answer);
13
14
  const answers = JSON.parse(answer.answers);
  answer.answers = answers;
Jiwon Yoon's avatar
Jiwon Yoon committed
15
16
17
18
  let files: any[] = [];
  if (Array.isArray(req.files.uploadFiles)) {
    files = req.files.uploadFiles as formidable.File[];
  } else {
19
20
21
    if (!isEmpty(req.files)) {
      files.push(req.files.uploadFiles);
    }
Jiwon Yoon's avatar
Jiwon Yoon committed
22
  }
Jiwon Yoon's avatar
Jiwon Yoon committed
23
  let uploadFile;
24
  try {
25
26
    if (files.length > 0) {
      console.log("files in answer controller:", files);
Jiwon Yoon's avatar
Jiwon Yoon committed
27
      // 1) 파일을 DB에 저장 후 다시 retFile가져와서
Jiwon Yoon's avatar
Jiwon Yoon committed
28
29
      // *근데 파일이 여러 개일 수 있기 때문에 순회해야 됨
      const f = files.map(async (file) => {
Jiwon Yoon's avatar
Jiwon Yoon committed
30
31
32
33
34
35
36
        uploadFile = new FileInfo({
          name: file.originalFilename,
          url: file.newFilename,
          isNew: true,
        });
        const retFile = await fileDb.createFile(file);
        // 2) answers의 type이 file인 친구들 찾아서 그 친구의 answer와 filename을 비교 후 같으면
Jiwon Yoon's avatar
Jiwon Yoon committed
37
38
39
        const targetObj = answer.answers.find(
          (ans: any) => ans.answer === file.originalFilename
        );
Jiwon Yoon's avatar
Jiwon Yoon committed
40
41
        // 3) answer에다가 retFile의 _id 넣어주기
        targetObj.answer = retFile._id;
Jiwon Yoon's avatar
Jiwon Yoon committed
42
43
      });
      await Promise.all(f);
44
    }
Jiwon Yoon's avatar
Jiwon Yoon committed
45
    // 3) Answer DB 만들기
Jiwon Yoon's avatar
Jiwon Yoon committed
46
47
48
49
50
    const c = answer.answers.map(async (element: any) => {
      const newAnswer = await answerDb.createAnswer({
        surveyId: answer.surveyId,
        guestId: answer.guestId,
        questionId: element.questionId,
51
        content: element.answer,
Jiwon Yoon's avatar
Jiwon Yoon committed
52
53
54
      });
    });
    await Promise.all(c);
55
56
    return res.json();
  } catch (error: any) {
Jiwon Yoon's avatar
Jiwon Yoon committed
57
    console.log("error in create answer:", error);
58
    // 오류 발생시 저장된 파일 제거
Jiwon Yoon's avatar
Jiwon Yoon committed
59
    if (req.files) {
Jiwon Yoon's avatar
Jiwon Yoon committed
60
61
      //   uploadFiles && (await fileDb.deleteFileById(uploadFiles._id.toString()));
      // await fs.unlink(files.filepath);
62
    }
Jiwon Yoon's avatar
Jiwon Yoon committed
63
    res.status(422).send(error.message || "설문조사 응답 생성 오류");
64
65
  }
});
Jiwon Yoon's avatar
Jiwon Yoon committed
66

67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
export const createAnswersWithoutFile = asyncWrap(async (req, res) => {
  const answers = req.body as IAnswer[];
  const newAnswers = await Promise.all(
    answers.map(
      async (answer) =>
        await answerDb.createAnswer({
          surveyId: answer.surveyId,
          guestId: answer.guestId,
          questionId: answer.questionId,
          content: answer.content,
        })
    )
  );

  console.log("new answers:", newAnswers);
  res.json(newAnswers);
});

export const createAnswerWithFile = asyncWrap(async (reqExp, res) => {
  const req = reqExp as TypedRequest;

  console.log("body:", req.body, "files:", req.files);
  const answer = req.body;

  let fileInfos;
  const files = formidableFilesToArray(req.files.uploadFiles);
Jiwon Yoon's avatar
Jiwon Yoon committed
93
  console.log("files=", files);
94
95
96
97
98
99
100
101
102
103
104
105
106
  if (files) {
    fileInfos = await Promise.all(
      files.map(async (file) => await fileDb.createFile(file))
    );
  }

  answer.content = fileInfos;
  const newAnswer = await answerDb.createAnswer(answer);

  console.log("new answer:", newAnswer);
  res.json(newAnswer);
});

Jiwon Yoon's avatar
Jiwon Yoon committed
107
108
109
110
export const getAnswers = asyncWrap(async (reqExp, res) => {
  const req = reqExp as TypedRequest;
  const { surveyId } = req.params;
  try {
Jiwon Yoon's avatar
Jiwon Yoon committed
111
    const result = await answerDb.getAnswers(surveyId);
112
    // console.log("result===", result);
Jiwon Yoon's avatar
Jiwon Yoon committed
113
    return res.json(result);
Jiwon Yoon's avatar
Jiwon Yoon committed
114
115
116
117
  } catch (error: any) {
    res.status(422).send(error.message || "설문조사 결과 불러오기 오류");
  }
});