import { NextFunction, Request, Response } from "express"; import isLength from "validator/lib/isLength"; import equals from "validator/lib/equals"; import { TypedRequestAuth } from "./auth.controller"; import { asyncWrap } from "../helpers"; import { postDb, userDb } from "../db"; import { TypedRequest } from "../types"; export const postCreate = asyncWrap(async (reqExp, res, next) => { const req = reqExp as TypedRequestAuth<{ userId: string }>; const { title, text, theme, city, date } = req.body as { title: string; text: string; theme: string; city: string; date: Date; counts: number; }; // 1) title 빈 문자열인지 확인 if (!isLength(title ?? "", { min: 1 })) { return res.status(422).send("제목을 한 글자 이상 입력해주세요"); } // 2) body 빈 문자열인지 확인 if (!isLength(text ?? "", { min: 1 })) { return res.status(422).send("제목을 한 글자 이상 입력해주세요"); } // 3) theme dropdown default-value "테마"일 경우 에러 if (equals(theme, "질문종류")) { return res.status(422).send("테마를 입력해 주세요"); } // 4) city dropdown default-value "도시"일 경우 에러 if (equals(city, "질문종류")) { return res.status(422).send("도시를 선택해 주세요"); } const userId = req.auth.userId; const newPost = await postDb.createPost({ title, text, theme, city, date: Date.now(), user: userId, }); console.log("post", newPost); return res.json(newPost); }); export const getAllPost = asyncWrap(async (req, res) => { const posts = await postDb.getPosts(); // console.log(posts); return res.json(posts); }); export const addCounts = asyncWrap(async (req, res) => { // console.log(req.body); const { postId } = req.params; const { counts } = req.body as { counts: number; }; console.log(postId, counts); const updateCounts = await postDb.addOneCount(postId, counts); return res.json(updateCounts); }); export const userByPostId = ( reqExp: Request, res: Response, next: NextFunction, postId: string ) => { const req = reqExp as TypedRequest; req.user = userDb.findUserByPostId(postId); next(); }; export const getOnePost = asyncWrap(async (req, res) => { const { postId } = req.params; const post = await postDb.getPost(postId); return res.json(post); }); export const deleteOnePost = asyncWrap(async (req, res) => { const { postId } = req.params; // console.log(postId); const deleteCount = await postDb.deletePost(postId); return res.json(deleteCount); }); export const updatePost = asyncWrap(async (reqExp, res) => { const req = reqExp as TypedRequestAuth<{ userId: string }>; const { title, text, theme, city, date } = req.body as { title: string; text: string; theme: string; city: string; date: Date; counts: number; }; const userId = req.auth.userId; const { postId } = req.params; const updatePost = await postDb.updateOnePost( { title, text, theme, city, date: Date.now(), counts: req.body.counts, user: userId, }, postId ); console.log("게시글 수정 후", updatePost); return res.json(updatePost); });