user.controller.ts 1.67 KB
Newer Older
Yoon, Daeki's avatar
Yoon, Daeki committed
1
2
import { userDb } from "../db";
import { asyncWrap } from "../helpers/asyncWrap";
Kim, MinGyu's avatar
Kim, MinGyu committed
3
import { Request } from "express";
4
5
6
import formidable, { Fields, Files } from "formidable";
import { ObjectId } from "mongoose";
import fs from "fs";
Kim, MinGyu's avatar
Kim, MinGyu committed
7
8
9
10

export interface TypedRequestAuth<T> extends Request {
  auth: T;
}
Yoon, Daeki's avatar
Yoon, Daeki committed
11
12
13
14
15
16
17
18
19
20

export const getUsers = asyncWrap(async (req, res) => {
  const users = await userDb.getUsers();
  return res.json(users);
});

export const createUser = asyncWrap(async (req, res) => {
  const user = req.body;
  console.log("user body", user);
  const newUser = await userDb.createUser(user);
Yoon, Daeki's avatar
Yoon, Daeki committed
21
  return res.json(newUser);
Yoon, Daeki's avatar
Yoon, Daeki committed
22
});
Kim, MinGyu's avatar
Kim, MinGyu committed
23
24

export const getProfile = asyncWrap(async (reqExp, res) => {
25
  const req = reqExp as TypedRequestAuth<{ userId: string }>; // 앞에서는 토큰으로써 사용하기 때문에 JwtPayload 를 사용하고 여기서는 verify 에서 토큰을 디코딩했기에 ObjectId 타입의 string으로 바뀌게 된다.
Kim, MinGyu's avatar
Kim, MinGyu committed
26

27
  const { userId } = req.auth;
Kim, MinGyu's avatar
Kim, MinGyu committed
28
  const profile = await userDb.getProfile(userId);
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
  res.json(profile);
});

export const postPicture = asyncWrap(async (reqExp, res) => {
  const req = reqExp as TypedRequestAuth<{ userId: ObjectId }>;
  const { userId } = req.auth;

  const form = formidable({
    uploadDir: "./src/upload",
    keepExtensions: true,
    multiples: false,
  });

  form.parse(req, (err, fields, files) => {
    if (!Array.isArray(files.picture)) {
      //파일 좁히기 중

      const originalfilename = files.picture.originalFilename;
      const newfilename = files.picture.newFilename;
      const picturepath = files.picture.filepath;
      userDb.postPicture(userId, originalfilename, newfilename, picturepath);
    }
  });
  res.json();
});