Commit fbaae34c authored by Lee Soobeom's avatar Lee Soobeom
Browse files

update debugging

parent c016fafd
import React, { FormEvent, useState, useEffect } from "react";
import React, { FormEvent, useState } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import isLength from "validator/lib/isLength";
import equals from "validator/lib/equals";
......@@ -6,20 +6,19 @@ import { catchErrors } from "../helpers";
import { PostType } from "../types";
import { postApi } from "../apis";
import { PostState } from "./intopost";
import { FileType } from "./intopost";
export function EditPost() {
const [city, setCity] = useState<string>("city");
const [theme, setTheme] = useState<string>("theme");
const location = useLocation() as PostState;
const post = location.state;
const [city, setCity] = useState<string>(post.city);
const [theme, setTheme] = useState<string>(post.theme);
const [title, setTitle] = useState<string>("");
const [text, setText] = useState<string>("");
const [file, setFile] = useState<FileList>();
const [imgSrc, setImgSrc] = useState<string[]>();
const [filesList, setFilesList] = useState<FileType[]>();
const [change, setChange] = useState<boolean>(false);
const navigate = useNavigate();
const location = useLocation() as PostState;
const post = location.state;
const [user, setUser] = useState<PostType>({
title: post.title,
......@@ -30,6 +29,7 @@ export function EditPost() {
user: post.user,
counts: post.counts,
_id: post._id,
file: post.file,
});
const [loading, setLoading] = useState(false);
......@@ -37,24 +37,17 @@ export function EditPost() {
const [disabled, setDisabled] = useState(false);
const [success, setSuccess] = useState(false);
useEffect(() => {
getFilesList(post._id);
}, []);
const getFilesList = async (postId: string) => {
const res = await postApi.getFileByPostId(postId);
setFilesList(res);
};
const imgArr = new Array();
const updateImg2Db = async (filelist: FileList) => {
// console.log("post.file", post.file);
const updateImg2Db = async (filelist: FileList | undefined) => {
const formdata = new FormData();
formdata.append("title", user.title);
formdata.append("text", user.text);
formdata.append("theme", user.theme);
formdata.append("city", user.city);
if (filelist === undefined || filelist === null) {
if (filelist === undefined) {
const res = await postApi.updateImgAndPost(user._id, formdata);
} else {
for (var i = 0; i < filelist.length; i++) {
......@@ -69,14 +62,12 @@ export function EditPost() {
try {
if (confirm("게시물을 수정하시겠습니까?") == true) {
setError("");
// console.log("user data", user);
if (postingFormMatch(user) === true) {
setLoading(true);
if (file) {
const res = updateImg2Db(file);
// console.log(res);
}
navigate("/board", { replace: true });
setSuccess(true);
setError("");
}
......@@ -92,9 +83,12 @@ export function EditPost() {
}
const handleInputPic = async (event: React.ChangeEvent<HTMLInputElement>) => {
setChange(true);
const maxImg = 10;
const { files } = event.target;
// console.log("update file", files);
if (!(files === null)) {
setFile(files);
}
......@@ -118,18 +112,18 @@ export function EditPost() {
function postingFormMatch(user: PostType) {
if (!isLength(user.title ?? "", { min: 1 })) {
setError("제목을 입력해 주세요.");
alert("제목을 입력해 주세요.");
setError("제목을 입력해 주세요.");
return false;
} else if (!isLength(user.text ?? "", { min: 1 })) {
alert("내용을 입력해 주세요.");
setError("내용을 입력해 주세요.");
return false;
} else if (equals(user.city, "city")) {
} else if (equals(city, "city")) {
alert("도시를 선택해 주세요.");
setError("도시를 선택해 주세요.");
return false;
} else if (equals(user.theme, "theme")) {
} else if (equals(theme, "theme")) {
alert("테마를 선택해 주세요.");
setError("테마를 선택해 주세요.");
return false;
......@@ -170,6 +164,26 @@ export function EditPost() {
setUser(newUser);
};
const oldFileShow = (post: PostType) => {
const res = post.file?.map((file, i) => (
<img
key={i}
src={"http://localhost:3000/images/" + file.newfilename}
width={200}
height={200}
/>
));
// console.log("oldfiles", res);
return res;
};
const newFileShow = (imgSrc: string[] | undefined) => {
const res = imgSrc?.map((img, i) => (
<img key={i} src={img} width={200} height={200} />
));
return res;
};
return (
<form onSubmit={reWriteSubmit} className="flex flex-col w-full">
<div className="flex flex-row h-10 gap-x-1 justify-end">
......@@ -236,6 +250,7 @@ export function EditPost() {
<div className="flex flex-col w-full border-y-2 border-sky-500">
<textarea
defaultValue={post.title}
name="title"
onChange={titleChange}
placeholder="제목을 입력해 주세요!"
......@@ -243,17 +258,11 @@ export function EditPost() {
/>
<div className="flex flex-col mt-1 mb-1 border-t-2 border-sky-200">
<div className="flex gap-x-2 h-44 overflow-x-auto ">
{filesList?.map((file, i) => (
<img
key={i}
src={"http://localhost:3000/images/" + file.newfilename}
width={200}
height={200}
/>
))}
{change ? newFileShow(imgSrc) : oldFileShow(post)}
</div>
</div>
<textarea
defaultValue={post.text}
onChange={textChange}
name="text"
placeholder="여행 후기를 알려주세요!"
......
......@@ -8,39 +8,16 @@ export interface PostState {
state: PostType;
}
export interface FileType {
id: string;
post: string;
originalfilename: string;
newfilename: string;
picturepath: string;
}
export interface FilesList {
filesList: FileType[];
}
export function IntoPost() {
const location = useLocation() as PostState;
const post = location.state;
const navigate = useNavigate();
const [filesList, setFilesList] = useState<FileType[]>();
// console.log(post);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const [addSuccess, setAddSuccess] = useState(false);
const [delSuccess, setDelSuccess] = useState(false);
useEffect(() => {
getFilesList(post._id);
}, []);
const getFilesList = async (postId: string) => {
const res = await postApi.getFileByPostId(postId);
setFilesList(res);
};
const handleDeleteClick = async (event: MouseEvent<HTMLButtonElement>) => {
try {
if (confirm("삭제하시겠습니까?") == true) {
......@@ -95,7 +72,7 @@ export function IntoPost() {
</div>
<div className="flex border-t-2 border-sky-200 h-44 p-2 overflow-auto mb-5 ">
{filesList?.map((file, i) => (
{post.file?.map((file, i) => (
<img
key={i}
src={"http://localhost:3000/images/" + file.newfilename}
......
......@@ -24,6 +24,13 @@ export default function Posting() {
user: "",
counts: 0,
_id: "",
file: [
{
originalfilename: "",
newfilename: "",
picturepath: "",
},
],
});
const [loading, setLoading] = useState(false);
......@@ -59,14 +66,12 @@ export default function Posting() {
if (confirm("게시물을 작성하시겠습니까?") == true) {
setError("");
// console.log("user data", user);
if (!(imgSrc === undefined)) {
if (postingFormMatch(user, imgSrc)) {
if (postingFormMatch(user, file)) {
setLoading(true);
if (file) {
const res = sendImg2Db(file);
// console.log(res);
}
}
navigate("/board", { replace: true });
setSuccess(true);
setError("");
......@@ -82,7 +87,7 @@ export default function Posting() {
}
}
function postingFormMatch(user: PostType, imgSrc: string[]) {
function postingFormMatch(user: PostType, file: FileList | undefined) {
if (!isLength(user.title ?? "", { min: 1 })) {
alert("제목을 입력해 주세요.");
setError("제목을 입력해 주세요.");
......@@ -91,6 +96,10 @@ export default function Posting() {
alert("내용을 입력해 주세요.");
setError("내용을 입력해 주세요.");
return false;
} else if (file === undefined) {
alert("사진을 첨부해 주세요.");
setError("사진을 첨부해 주세요.");
return false;
} else if (equals(city, "city")) {
alert("도시를 선택해 주세요.");
setError("도시를 선택해 주세요.");
......@@ -99,10 +108,6 @@ export default function Posting() {
alert("테마를 선택해 주세요.");
setError("테마를 선택해 주세요.");
return false;
} else if (imgSrc === undefined || imgSrc === null) {
alert("사진을 첨부해 주세요.");
setError("사진을 첨부해 주세요.");
return false;
} else {
return true;
}
......
......@@ -21,6 +21,13 @@ export interface PostType {
counts: number;
_id: string;
user: string;
file: [
{
originalfilename: string;
newfilename: string;
picturepath: string;
}
];
}
export interface SignupUser {
......@@ -32,8 +39,7 @@ export interface SignupUser {
export interface Profile {
_id: string;
email: string;
name: string;
avatar: {
fileInfo: {
originalfilename: string;
newfilename: string;
picturepath: string;
......
import { NextFunction, Request, Response } from "express";
import formidable, { Fields, Files } from "formidable";
import { TypedRequestAuth } from "./auth.controller";
import equals from "validator/lib/equals";
import { asyncWrap } from "../helpers";
import { postDb, userDb } from "../db";
import { TypedRequest } from "../types";
import { Types } from "mongoose";
export const userByPostId = (
reqExp: Request,
......@@ -16,6 +18,60 @@ export const userByPostId = (
next();
};
export const subTract = (oldSet: Set<string>, newSet: Set<string>) => {
const keep = new Array<string>(); //유지
const drop = new Array<string>(); //삭제
const add = new Array<string>(); //추가
oldSet.forEach((oldname) => {
drop.push(oldname);
newSet.forEach((newname) => {
add.push(newname);
if (oldname === newname) {
keep.push(oldname);
}
});
});
const addSet = new Set(add);
const newAdd = [...addSet];
// console.log("before delete drop ", drop);
// console.log("before delete add ", add);
for (var i = 0; i < drop.length; i++) {
for (var j = 0; j < keep.length; j++) {
if (drop[i] === keep[j]) {
drop.splice(i, 1);
}
}
}
for (var i = 0; i < newAdd.length; i++) {
for (var j = 0; j < keep.length; j++) {
if (newAdd[i] === keep[j]) {
newAdd.splice(i, 1);
}
}
}
// console.log("spliced add", add);
const dropSet = new Set(drop);
const newDrop = [...dropSet];
const reAddSet = new Set(newAdd);
const reNewAdd = [...reAddSet];
const res = {
keep: keep,
drop: newDrop,
add: reNewAdd,
};
return res;
};
//Create
export const createFileAndPost = asyncWrap(async (reqExp, res, next) => {
const req = reqExp as TypedRequestAuth<{ userId: string }>;
......@@ -112,23 +168,22 @@ export const addCounts = asyncWrap(async (req, res) => {
return res.json(updateCounts);
});
export const updatePost = asyncWrap(async (reqExp, res) => {
export const updateOnePost = asyncWrap(async (reqExp, res) => {
const req = reqExp as TypedRequestAuth<{ userId: string }>;
const userId = req.auth.userId;
const { userId } = req.auth;
const { postId } = req.params;
const oldSet = new Set<string>();
const newSet = new Set<string>();
const fileIdArr = new Array<Types.ObjectId>();
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;
......@@ -138,82 +193,97 @@ export const updatePost = asyncWrap(async (reqExp, res) => {
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);
console.log("check files", files);
if (files.picture === undefined || files.picture === null) {
const postRes2 = await postDb.updatePostRow(
{
title,
text,
theme,
city,
date: Date.now(),
},
postId
);
console.log("no files update", postRes2);
} else {
const oldFilesId = await postDb.getFilesByPostId(postId);
if (!(oldFilesId === undefined)) {
for (var i = 0; i < oldFilesId?.length; i++) {
const name = await postDb.getOriginalFileName(oldFilesId[i]);
if (!(name === undefined)) {
oldSet.add(name);
}
}
}
console.log("OldSet", oldSet);
if (Array.isArray(files.picture)) {
for (var i = 0; i < files.picture.length; i++) {
const newFileName = files.picture?.[i].originalFilename;
if (!(newFileName === undefined)) {
if (!(newFileName === undefined || newFileName === null)) {
newSet.add(newFileName);
}
}
}
console.log("NewSet", newSet);
//유지, 삭제, 추가 구분하기
const trdPart = subTract(oldSet, newSet);
const deleteFiles = new Array();
const addFiles = new Array();
console.log("keep", trdPart.keep);
console.log("drop", trdPart.drop);
console.log("add", trdPart.add);
oldSet.forEach((oldName) => {
newSet.forEach((newName) => {
if (!(oldName === newName)) {
deleteFiles.push(oldName);
addFiles.push(newName);
// 삭제
for (var i = 0; i < trdPart.drop.length; i++) {
const dropRes = await postDb.deleteFileByName(trdPart.drop[i]);
console.log("delete counts", dropRes);
}
});
});
for (var i = 0; i < deleteFiles.length; i++) {
const originalfilename = deleteFiles[i];
const delRes = await postDb.deleteFileByName(originalfilename);
//유지
for (var i = 0; i < trdPart.keep.length; i++) {
const keepRes = await postDb.findByName(trdPart.keep[i]);
fileIdArr.push(keepRes[0]._id);
// console.log("keep Id", keepRes[0]._id);
}
//추가
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) {
for (var j = 0; j < trdPart.add.length; j++) {
const check = trdPart.add[j];
if (originalfilename === check) {
const addRes = await postDb.createFilesRow(
originalfilename,
newfilename,
filepath
);
fileIdArr.push(addRes);
fileIdArr.push(addRes._id);
}
}
}
}
console.log("all fileId", fileIdArr);
const updateRes = await postDb.updatedFileId(postId);
const fileId = fileIdArr.concat(updateRes);
const postRes = await postDb.updatePostRow(
//post정보 + file정보 update
const postRes1 = await postDb.updatePostRow(
{
title,
text,
theme,
city,
date: Date.now(),
user: userId,
file: fileId,
file: fileIdArr,
},
postId
);
console.log("plzplzplzpllzplzlpzplzzplz", postRes);
return res.json(postRes);
}
}
}
......@@ -222,19 +292,11 @@ export const updatePost = asyncWrap(async (reqExp, res) => {
});
});
//Delete
// 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);
if (!(deleteFileId === undefined)) {
for (var i = 0; i < deleteFileId.length; i++) {
const deleteId = deleteFileId[i];
const deleteFile = await postDb.deleteFile(deleteId);
}
}
const deleteCount = await postDb.deletePost(postId);
return res.json(deleteCount);
});
import { Types, ObjectId } from "mongoose";
import fs from "fs/promises";
import { Post, PostType } from "../models";
import { FileInfo, IFileInfo } from "../models";
......@@ -33,15 +34,11 @@ export const createFilesRow = async (
//Read
export const getPosts = async () => {
const posts = await Post.find({}).sort({ date: -1 });
const posts = await Post.find().populate("file").sort({ date: -1 });
console.log(posts);
return posts;
};
export const getFilesByPostId = async (postId: string) => {
const files = await Post.findOne({ _id: postId }).populate("file");
return files?.file;
};
//Update
export const addOneCount = async (_id: string, counts: number) => {
const newCounts = await Post.findOneAndUpdate(
......@@ -61,7 +58,6 @@ export const updatePostRow = async (post: PostType, postId: string) => {
theme: post.theme,
city: post.city,
date: post.date,
user: post.user,
file: post.file,
},
{ new: true }
......@@ -69,6 +65,11 @@ export const updatePostRow = async (post: PostType, postId: string) => {
return newPost;
};
export const getFilesByPostId = async (postId: string) => {
const files = await Post.findOne({ _id: postId }).populate("file");
return files?.file; //file Types.ObjectId[]
};
export const getOriginalFileName = async (_id: Types.ObjectId) => {
const file = await FileInfo.findOne({ _id: _id });
return file?.originalfilename;
......@@ -79,15 +80,26 @@ export const updatedFileId = async (_id: string) => {
return updatedFile?.file;
};
export const findByName = async (originalfilename: string) => {
const fileId = await FileInfo.find({ originalfilename });
return fileId;
};
//Delete
export const deletePost = async (_id: string) => {
const post = await Post.findById(_id);
if (!(post?.file === undefined)) {
for (var i = 0; i < post.file.length; i++) {
const fileId = post.file[i];
const ref = await FileInfo.findById(fileId);
if (!(ref?.newfilename === undefined)) {
await fs.unlink("../travel/uploads/" + ref?.newfilename);
}
await FileInfo.deleteOne({ _id: fileId });
}
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) => {
......
......@@ -7,7 +7,7 @@ export interface PostType {
city: string;
date: Date | number;
counts?: number;
user: Types.ObjectId | string;
user?: Types.ObjectId | string;
file?: Array<Types.ObjectId>;
}
......
......@@ -13,7 +13,7 @@ router
.route("/:postId")
.post(authCtrl.requireLogin, postCtrl.addCounts)
.delete(authCtrl.requireLogin, postCtrl.deleteOnePost) // +authenticate
.put(authCtrl.requireLogin, postCtrl.updatePost);
.put(authCtrl.requireLogin, postCtrl.updateOnePost);
router.param("postId", postCtrl.userByPostId);
export default router;
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment