diff --git a/frontend/src/apis/post.api.ts b/frontend/src/apis/post.api.ts
index d8e2a17c76e1157eb5e6869a79637c4d0a9ad25e..ef2ab87323db478359bd9900cf6675617de74019 100644
--- a/frontend/src/apis/post.api.ts
+++ b/frontend/src/apis/post.api.ts
@@ -2,26 +2,24 @@ import axios from "axios";
import baseUrl from "./baseUrl";
import { PostType } from "../types";
+//Create
export const createFileAndPost = async (formdata: FormData) => {
const { data } = await axios.post(`${baseUrl}/posts/`, formdata);
return data;
};
+//Read
export const getData = async () => {
const { data } = await axios.get(`${baseUrl}/posts/`);
return data;
-}; //board
+};
export const getFileByPostId = async (postId: string) => {
const { data } = await axios.get(`${baseUrl}/posts/files/${postId}`);
return data;
-}; //
-
-export const getImgData = async (name: string) => {
- const { data } = await axios.get(`/images/${name}`);
- return data;
};
+//Update
export const addCounts = async (postId: string, counts: number) => {
const { data } = await axios.post(`${baseUrl}/posts/${postId}`, {
counts: counts + 1,
@@ -29,12 +27,13 @@ export const addCounts = async (postId: string, counts: number) => {
return data;
};
-export const deletePost = async (postId: string) => {
- const { data } = await axios.delete(`${baseUrl}/posts/${postId}`);
+export const updateImgAndPost = async (postId: string, formdata: FormData) => {
+ const { data } = await axios.put(`${baseUrl}/posts/${postId}`, formdata);
return data;
};
-export const updateImgAndPost = async (postId: string, formdata: FormData) => {
- const { data } = await axios.put(`${baseUrl}/posts/${postId}`, formdata);
+//Delete
+export const deletePost = async (postId: string) => {
+ const { data } = await axios.delete(`${baseUrl}/posts/${postId}`);
return data;
};
diff --git a/frontend/src/board/board.tsx b/frontend/src/board/board.tsx
index 8c4f7a77f4d7aadf830832b01de150c579e58746..2d9987d7558b6551da583d5a81ce2fe45743a93f 100644
--- a/frontend/src/board/board.tsx
+++ b/frontend/src/board/board.tsx
@@ -13,7 +13,7 @@ export default function BoardPage() {
useEffect(() => {
getDataList();
- }, []);
+ }, [posts]);
// posts
const getDataList = async () => {
const res = await postApi.getData();
diff --git a/frontend/src/post/editpost.tsx b/frontend/src/post/editpost.tsx
index 67a03b06583db5caeda534e433a62afbf1b54024..28b080d13af63efda457a86b5f8ba109a0c86b4e 100644
--- a/frontend/src/post/editpost.tsx
+++ b/frontend/src/post/editpost.tsx
@@ -41,13 +41,13 @@ export function EditPost() {
getFilesList(post._id);
}, []);
- const imgArr = new Array();
-
const getFilesList = async (postId: string) => {
- const res = await postApi.getFileByPostId(postId); //_id는 req.params에 항상 같이 보낸다
+ const res = await postApi.getFileByPostId(postId);
setFilesList(res);
};
+ const imgArr = new Array();
+
const updateImg2Db = async (filelist: FileList) => {
const formdata = new FormData();
formdata.append("title", user.title);
@@ -250,6 +250,7 @@ export function EditPost() {
onChange={titleChange}
placeholder="제목을 입력해 주세요!"
className="flex w-96 border-2 border-sky-500 rounded"
+ defaultValue={post.title}
/>
@@ -268,6 +269,7 @@ export function EditPost() {
name="text"
placeholder="여행 후기를 알려주세요!"
className="flex w-96 h-96 border-2 border-sky-500 rounded"
+ defaultValue={post.text}
/>
diff --git a/frontend/src/post/intopost.tsx b/frontend/src/post/intopost.tsx
index 4e8ed51330ddaa628f8488eaf6e0f45725d9c06d..e8ce1ed9bef5aeb68344821f7ec33639cb78ae1d 100644
--- a/frontend/src/post/intopost.tsx
+++ b/frontend/src/post/intopost.tsx
@@ -34,7 +34,6 @@ export function IntoPost() {
useEffect(() => {
getFilesList(post._id);
- console.log("newfilename", filesList?.[0].newfilename);
}, []);
const getFilesList = async (postId: string) => {
diff --git a/src/controllers/post.controller.ts b/src/controllers/post.controller.ts
index 3bfee3a3abcd7c5006e41828fb5f721a0de22ca6..45d58014981a6751830cdc4d5dc976b0342476fd 100644
--- a/src/controllers/post.controller.ts
+++ b/src/controllers/post.controller.ts
@@ -5,6 +5,18 @@ import { asyncWrap } from "../helpers";
import { postDb, userDb } from "../db";
import { TypedRequest } from "../types";
+export const userByPostId = (
+ reqExp: Request,
+ res: Response,
+ next: NextFunction,
+ postId: string
+) => {
+ const req = reqExp as TypedRequest;
+ req.user = userDb.findUserByPostId(postId);
+ next();
+};
+
+//Create
export const createFileAndPost = asyncWrap(async (reqExp, res, next) => {
const req = reqExp as TypedRequestAuth<{ userId: string }>;
@@ -66,6 +78,8 @@ export const createFileAndPost = asyncWrap(async (reqExp, res, next) => {
user: userId,
file: fileIdArr,
});
+
+ return res.json(postRes);
}
}
}
@@ -73,88 +87,154 @@ export const createFileAndPost = asyncWrap(async (reqExp, res, next) => {
});
});
+//Read
export const getAllPost = asyncWrap(async (req, res) => {
const posts = await postDb.getPosts();
- // console.log(posts);
return res.json(posts);
});
export const getFiles = asyncWrap(async (req, res) => {
const { postId } = req.params;
- // console.log("나는 말하는 고구마.", postId);
const files = await postDb.getFilesByPostId(postId);
return res.json(files);
});
+//Update
export const addCounts = asyncWrap(async (req, res) => {
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 updatePost = asyncWrap(async (reqExp, res) => {
+ const req = reqExp as TypedRequestAuth<{ userId: string }>;
-export const getOnePost = asyncWrap(async (req, res) => {
+ const userId = req.auth.userId;
const { postId } = req.params;
- const post = await postDb.getPost(postId);
- return res.json(post);
+ const form = formidable({
+ uploadDir: "uploads",
+ keepExtensions: true,
+ multiples: true,
+ });
+
+ const fileIdArr = new Array();
+
+ const oldSet = new Set();
+ const newSet = new Set();
+
+ form.parse(req, async (err, fields, files) => {
+ if (!Array.isArray(fields.title)) {
+ const title = fields.title;
+ if (!Array.isArray(fields.text)) {
+ const text = fields.text;
+ if (!Array.isArray(fields.theme)) {
+ const theme = fields.theme;
+ if (!Array.isArray(fields.city)) {
+ const city = fields.city;
+ if (!Array.isArray(fields.change)) {
+ const change = fields.change;
+
+ const oldFiles = await postDb.getFilesByPostId(postId);
+ if (!(oldFiles === undefined)) {
+ for (var i = 0; (i = oldFiles.length); i++) {
+ const oldFileName = postDb.getOriginalFileName(oldFiles[i]);
+ if (!(oldFileName === undefined)) {
+ oldSet.add(oldFileName);
+ }
+ }
+ }
+
+ if (Array.isArray(files.picture)) {
+ for (var i = 0; i < files.picture.length; i++) {
+ const newFileName = files.picture?.[i].originalFilename;
+ if (!(newFileName === undefined)) {
+ newSet.add(newFileName);
+ }
+ }
+ }
+
+ const deleteFiles = new Array();
+ const addFiles = new Array();
+
+ oldSet.forEach((oldName) => {
+ newSet.forEach((newName) => {
+ if (!(oldName === newName)) {
+ deleteFiles.push(oldName);
+ addFiles.push(newName);
+ }
+ });
+ });
+
+ for (var i = 0; i < deleteFiles.length; i++) {
+ const originalfilename = deleteFiles[i];
+ const delRes = await postDb.deleteFileByName(originalfilename);
+ }
+
+ if (Array.isArray(files.picture)) {
+ for (var i = 0; i < files.picture.length; i++) {
+ const originalfilename = files.picture?.[i].originalFilename;
+ const newfilename = files.picture?.[i].newFilename;
+ const filepath = files.picture?.[i].filepath;
+ for (var i = 0; i < addFiles.length; i++) {
+ const original = addFiles[i];
+ if (original === originalfilename) {
+ const addRes = await postDb.createFilesRow(
+ originalfilename,
+ newfilename,
+ filepath
+ );
+
+ fileIdArr.push(addRes);
+ }
+ }
+ }
+ }
+
+ const updateRes = await postDb.updatedFileId(postId);
+ const fileId = fileIdArr.concat(updateRes);
+
+ const postRes = await postDb.updatePostRow(
+ {
+ title,
+ text,
+ theme,
+ city,
+ date: Date.now(),
+ user: userId,
+ file: fileId,
+ },
+ postId
+ );
+ console.log("plzplzplzpllzplzlpzplzzplz", postRes);
+ return res.json(postRes);
+ }
+ }
+ }
+ }
+ }
+ });
});
+//Delete
export const deleteOnePost = asyncWrap(async (req, res) => {
const { postId } = req.params;
// console.log(postId);
const deleteCount = await postDb.deletePost(postId);
+ const deleteFileId = await postDb.getFilesByPostId(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;
+ if (!(deleteFileId === undefined)) {
+ for (var i = 0; i < deleteFileId.length; i++) {
+ const deleteId = deleteFileId[i];
+ const deleteFile = await postDb.deleteFile(deleteId);
+ }
+ }
- 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);
+ return res.json(deleteCount);
});
diff --git a/src/db/mainimg.db.ts b/src/db/mainimg.db.ts
index 6ef6e72874d6466565cd807f563a957d51d52b96..e484c27d575a345fdb4677a0a51362f9eca9087a 100644
--- a/src/db/mainimg.db.ts
+++ b/src/db/mainimg.db.ts
@@ -18,7 +18,7 @@ export const createMainimg = async (mainimg: MainimgType, pic: IFileInfo) => {
};
export const getMainimg = async () => {
- const img = await Mainimg.find({}).populate("pic");
+ const img = await Mainimg.find({}).populate("fileInfo");
return img;
};
diff --git a/src/db/post.db.ts b/src/db/post.db.ts
index d7d8ee3c389484236bfe7d7974d4ef80f2346127..68f04795e0ed989bd2c62e12cb10be820afe6bda 100644
--- a/src/db/post.db.ts
+++ b/src/db/post.db.ts
@@ -2,6 +2,7 @@ import { Types, ObjectId } from "mongoose";
import { Post, PostType } from "../models";
import { FileInfo, IFileInfo } from "../models";
+//Create
export const createPostRow = async (post: PostType) => {
const newPostRow = await Post.create({
title: post.title,
@@ -30,6 +31,7 @@ export const createFilesRow = async (
return newFileRow._id;
};
+//Read
export const getPosts = async () => {
const posts = await Post.find({}).sort({ date: -1 });
return posts;
@@ -40,6 +42,7 @@ export const getFilesByPostId = async (postId: string) => {
return files?.file;
};
+//Update
export const addOneCount = async (_id: string, counts: number) => {
const newCounts = await Post.findOneAndUpdate(
{ _id: _id },
@@ -49,29 +52,45 @@ export const addOneCount = async (_id: string, counts: number) => {
return newCounts;
};
-export const getPost = async (_id: string) => {
- const post = await Post.findOne({ _id: _id });
- return post;
-};
-
-export const deletePost = async (_id: string) => {
- const res = await Post.deleteOne({ _id: _id });
- return res;
-};
-
-export const updateOnePost = async (post: PostType, _id: string) => {
+export const updatePostRow = async (post: PostType, postId: string) => {
const newPost = await Post.findOneAndUpdate(
- { _id: _id },
+ { _id: postId },
{
title: post.title,
text: post.text,
theme: post.theme,
city: post.city,
date: post.date,
- counts: post.counts,
user: post.user,
+ file: post.file,
},
{ new: true }
);
return newPost;
};
+
+export const getOriginalFileName = async (_id: Types.ObjectId) => {
+ const file = await FileInfo.findOne({ _id: _id });
+ return file?.originalfilename;
+};
+
+export const updatedFileId = async (_id: string) => {
+ const updatedFile = await Post.findOne({ _id: _id }).populate("file");
+ return updatedFile?.file;
+};
+
+//Delete
+export const deletePost = async (_id: string) => {
+ const res = await Post.deleteOne({ _id: _id });
+ return res;
+};
+
+export const deleteFile = async (_id: Types.ObjectId) => {
+ const deleteOne = await FileInfo.deleteOne({ _id: _id });
+ return deleteOne;
+};
+
+export const deleteFileByName = async (originalfilename: string) => {
+ const deleteFile = await FileInfo.deleteOne({ originalfilename });
+ return deleteFile;
+};
diff --git a/src/routes/post.route.ts b/src/routes/post.route.ts
index ad2dc5142e4a32f0f4006fe24fb8adfcf9376bd1..df02fc9fc52cb6752a885270d96ff9acfe492900 100644
--- a/src/routes/post.route.ts
+++ b/src/routes/post.route.ts
@@ -12,7 +12,6 @@ router.route("/files/:postId").get(authCtrl.requireLogin, postCtrl.getFiles);
router
.route("/:postId")
.post(authCtrl.requireLogin, postCtrl.addCounts)
- .get(authCtrl.requireLogin, postCtrl.getOnePost)
.delete(authCtrl.requireLogin, postCtrl.deleteOnePost) // +authenticate
.put(authCtrl.requireLogin, postCtrl.updatePost);