import { NextFunction, Request, Response } from "express"; import isLength from "validator/lib/isLength"; import { TypedRequestAuth } from "./auth.controller"; import { asyncWrap } from "../helpers"; import { mainimgDb } from "../db"; import { TypedRequest } from "../types"; import { ObjectId } from "mongoose"; import formidable from "formidable"; export const createMainimg = asyncWrap(async (reqExp, res) => { const req = reqExp as TypedRequestAuth<{ userId: ObjectId }>; const { userId } = req.auth; const form = formidable({ uploadDir: "uploads", keepExtensions: true, multiples: false, }); form.parse(req, (err, fields, files) => { if (!Array.isArray(files.mainimg)) { //파일 좁히기 중 if ( !( Array.isArray(fields.city) || Array.isArray(fields.title) || Array.isArray(fields.theme) ) ) { const city = fields.city; const title = fields.title; const theme = fields.theme; const originalfilename = files.mainimg?.originalFilename; const newfilename = files.mainimg.newFilename; if (!(originalfilename === null || newfilename === undefined)) { mainimgDb.createMainimg( { city, title, theme }, { originalfilename, newfilename, } ); } } } }); res.json(); }); // if (!isLength(url ?? "", { min: 1 })) { // return res.status(422).send("이미지 url을 입력해주세요"); // } // if (!isLength(title ?? "", { min: 1 })) { // return res.status(422).send("이미지 제목을 입력해주세요"); // } // const newMainimg = await mainimgDb.createMainimg({ // theme, // city, // url, // title, // }); // return res.json(newMainimg); // }); export const getMainimg = asyncWrap(async (req, res) => { const mainimgs = await mainimgDb.getMainimg(); return res.json(mainimgs); }); export const deleteMainimg = asyncWrap(async (req, res) => { const { imgId } = req.params; console.log(imgId); const deleteCount = await mainimgDb.deleteOneMainimg(imgId); return res.json(deleteCount); }); export const updateMainimg = asyncWrap(async (reqExp, res) => { const req = reqExp as TypedRequestAuth<{ userId: ObjectId }>; const form = formidable({ uploadDir: "uploads", keepExtensions: true, multiples: false, }); form.parse(req, (err, fields, files) => { if (!Array.isArray(files.updatemainimg)) { //파일 좁히기 중 if ( !( Array.isArray(fields.id) || Array.isArray(fields.city) || Array.isArray(fields.title) || Array.isArray(fields.theme) ) ) { const id = fields.id; const city = fields.city; const title = fields.title; const theme = fields.theme; console.log("error"); if (!(files.updatemainimg === undefined)) { const originalfilename = files.updatemainimg?.originalFilename; const newfilename = files.updatemainimg.newFilename; if (!(originalfilename === null || newfilename === undefined)) { mainimgDb.updateOneMainimg( id, theme, city, title, originalfilename, newfilename ); } } else { mainimgDb.updateOneMainimg(id, theme, city, title); } } } }); res.json(); });