import { NextFunction, Request, Response } from "express"; import formidable, { Fields, Files } from "formidable"; import { TypedRequestAuth } from "./auth.controller"; import { asyncWrap } from "../helpers"; import { postDb, userDb } from "../db"; import { TypedRequest } from "../types"; export const createImgAndPost = asyncWrap(async (reqExp, res, next) => { const req = reqExp as TypedRequestAuth<{ userId: string }>; // const { date, counts } = req.body as { // date: ""; // counts: 0; // }; const { userId } = req.auth; const form = formidable({ uploadDir: "uploads", keepExtensions: true, multiples: true, }); const fileIdArr = new Array(); form.parse(req, (err, fields, files) => { const title = fields.title?.[0]; const text = fields.text?.[0]; const theme = fields.theme?.[0]; const city = fields.city?.[0]; if (Array.isArray(files.picture)) { for (var i = 0; i < files.picture.length; i++) { if (!(files.picture?.[i].originalFilename === null)) { const originalfilename = files.picture?.[i].originalFilename; const newfilename = files.picture?.[i].newFilename; const filepath = files.picture?.[i].filepath; const filesRes = postDb.createFilesRow( originalfilename, newfilename, filepath ); } } } else { console.log("업로드한 사진이 없습니다."); } const postRes = postDb.createPostRow({ title, text, theme, city, date: Date.now(), counts: 0, user: userId, }); console.log("createPostRow", postRes); }); }); 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); });