post.controller.ts 1.44 KB
Newer Older
Lee Soobeom's avatar
Lee Soobeom committed
1
import { NextFunction, Request, Response } from "express";
2
3
import isLength from "validator/lib/isLength";
import equals from "validator/lib/equals";
Lee Soobeom's avatar
Lee Soobeom committed
4
import { TypedRequestAuth } from "./auth.controller";
Lee Soobeom's avatar
Lee Soobeom committed
5
import { asyncWrap } from "../helpers";
Lee Soobeom's avatar
Lee Soobeom committed
6
import { postDb } from "../db";
Lee Soobeom's avatar
Lee Soobeom committed
7

Lee Soobeom's avatar
Lee Soobeom committed
8
9
export const postCreate = asyncWrap(async (reqExp, res, next) => {
  const req = reqExp as TypedRequestAuth<{ userId: string }>;
Lee Soobeom's avatar
Lee Soobeom committed
10

Lee Soobeom's avatar
Lee Soobeom committed
11
12
13
14
15
16
17
  const { title, text, theme, city, date } = req.body as {
    title: string;
    text: string;
    theme: string;
    city: string;
    date: Date;
  };
Lee Soobeom's avatar
Lee Soobeom committed
18

Lee Soobeom's avatar
Lee Soobeom committed
19
  console.log("body", req.body);
Lee Soobeom's avatar
Lee Soobeom committed
20

21
22
23
24
  // 1) title 빈 문자열인지 확인
  if (!isLength(title ?? "", { min: 1 })) {
    return res.status(422).send("제목을 한 글자 이상 입력해주세요");
  }
Lee Soobeom's avatar
Lee Soobeom committed
25

26
27
28
29
  // 2) body 빈 문자열인지 확인
  if (!isLength(text ?? "", { min: 1 })) {
    return res.status(422).send("제목을 한 글자 이상 입력해주세요");
  }
Lee Soobeom's avatar
Lee Soobeom committed
30

Lee Soobeom's avatar
Lee Soobeom committed
31
  // 3) theme dropdown default-value "테마"일 경우 에러
32
33
34
  if (equals(theme, "질문종류")) {
    return res.status(422).send("테마를 입력해 주세요");
  }
Lee Soobeom's avatar
Lee Soobeom committed
35

Lee Soobeom's avatar
Lee Soobeom committed
36
  // 4) city dropdown default-value "도시"일 경우 에러
37
38
39
  if (equals(city, "질문종류")) {
    return res.status(422).send("도시를 선택해 주세요");
  }
Lee Soobeom's avatar
Lee Soobeom committed
40

Lee Soobeom's avatar
Lee Soobeom committed
41
  const userId = req.auth.userId;
Lee Soobeom's avatar
Lee Soobeom committed
42

Lee Soobeom's avatar
Lee Soobeom committed
43
  const newPost = await postDb.createPost({
Lee Soobeom's avatar
Lee Soobeom committed
44
45
46
47
    title,
    text,
    theme,
    city,
Lee Soobeom's avatar
Lee Soobeom committed
48
    date,
Lee Soobeom's avatar
Lee Soobeom committed
49
    user: userId,
Lee Soobeom's avatar
Lee Soobeom committed
50
  });
Lee Soobeom's avatar
Lee Soobeom committed
51
52

  return res.json(newPost);
53
});