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

export const createAnswers = asyncWrap(async (reqExp, res) => {
  const req = reqExp as TypedRequest;
  const answer = req.body;
  const answers = JSON.parse(answer.answers);
  answer.answers = answers;
Jiwon Yoon's avatar
Jiwon Yoon committed
14
15
16
17
18
19
  let files: any[] = [];
  if (Array.isArray(req.files.uploadFiles)) {
    files = req.files.uploadFiles as formidable.File[];
  } else {
    files.push(req.files.uploadFiles);
  }
Jiwon Yoon's avatar
Jiwon Yoon committed
20
  let uploadFile;
21
  try {
Jiwon Yoon's avatar
Jiwon Yoon committed
22
23
    if (files) {
      // 1) 파일을 DB에 저장 후 다시 retFile가져와서
Jiwon Yoon's avatar
Jiwon Yoon committed
24
25
      // *근데 파일이 여러 개일 수 있기 때문에 순회해야 됨
      const f = files.map(async (file) => {
Jiwon Yoon's avatar
Jiwon Yoon committed
26
27
28
29
30
31
32
        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
33
34
35
        const targetObj = answer.answers.find(
          (ans: any) => ans.answer === file.originalFilename
        );
Jiwon Yoon's avatar
Jiwon Yoon committed
36
37
        // 3) answer에다가 retFile의 _id 넣어주기
        targetObj.answer = retFile._id;
Jiwon Yoon's avatar
Jiwon Yoon committed
38
39
      });
      await Promise.all(f);
40
    }
Jiwon Yoon's avatar
Jiwon Yoon committed
41
    // 3) Answer DB 만들기
Jiwon Yoon's avatar
Jiwon Yoon committed
42
43
44
45
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,
        answer: element.answer,
      });
    });
    await Promise.all(c);
51
52
    return res.json();
  } catch (error: any) {
Jiwon Yoon's avatar
Jiwon Yoon committed
53
    console.log("error in create answer:", error);
54
    // 오류 발생시 저장된 파일 제거
Jiwon Yoon's avatar
Jiwon Yoon committed
55
    if (req.files) {
Jiwon Yoon's avatar
Jiwon Yoon committed
56
57
      //   uploadFiles && (await fileDb.deleteFileById(uploadFiles._id.toString()));
      // await fs.unlink(files.filepath);
58
    }
Jiwon Yoon's avatar
Jiwon Yoon committed
59
    res.status(422).send(error.message || "설문조사 응답 생성 오류");
60
61
  }
});
Jiwon Yoon's avatar
Jiwon Yoon committed
62
63
64
65
66

export const getAnswers = asyncWrap(async (reqExp, res) => {
  const req = reqExp as TypedRequest;
  const { surveyId } = req.params;
  try {
Jiwon Yoon's avatar
Jiwon Yoon committed
67
    const survey = await surveyDb.getSurveyById(surveyId);
Jiwon Yoon's avatar
Jiwon Yoon committed
68
    const answers = await answerDb.getAnswers(surveyId);
Jiwon Yoon's avatar
Jiwon Yoon committed
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
    console.log(answers);
    const jsonSurvey = survey?.toJSON();
    if (jsonSurvey && answers) {
      const a = answers.map(async (a) => {
        const targetObj = jsonSurvey.questions.find(
          (q: any) => String(q._id) === String(a._id)
        ) as any;
        if (targetObj) {
          if (a.file.length) {
            targetObj.answers = a.file;
          } else {
            targetObj.answers = a.answers;
          }
        }
      });
      await Promise.all(a);
    }
    return res.json(jsonSurvey);
Jiwon Yoon's avatar
Jiwon Yoon committed
87
88
89
90
  } catch (error: any) {
    res.status(422).send(error.message || "설문조사 결과 불러오기 오류");
  }
});