file.controller.ts 832 Bytes
Newer Older
Yoon, Daeki's avatar
Yoon, Daeki committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { NextFunction, Request, Response } from "express";
import formidable from "formidable";
import { isEmpty } from "../helpers";
import { asyncWrap } from "../helpers/asyncWrap";

interface TypedRequest extends Request {
  auth: any;
  user: any;
  files: any;
}

export const fileUpload = asyncWrap(async (req, res, next) => {
  const typedReq = req as TypedRequest;

  const form = formidable();
  await new Promise((resolve, reject) => {
    form.parse(req, (err, fields, files) => {
      if (err) {
        reject(err);
        return;
      }

      console.log("fields", fields);
      console.log("files", files);
      typedReq.body = fields;

      if (isEmpty(files)) {
        typedReq.files = null;
      } else {
        typedReq.files = files;
      }
      resolve(files);
    });
  });
  next();
  return;
});