2 글 보임 - 1 에서 2 까지 (총 2 중에서)
-
글쓴이글
-
2023년 8월 23일 16:56 #95598
정민규참가자import { connectDB } from "@/util/database"; import { ObjectId } from "mongodb";
export default async function handler(req, res) { if (req.method === "POST") { let data = JSON.parse(req.body);
const db = (await connectDB).db("forum");
const newLike = { clickedUser: data.userEmail, postId: data.postId, };
let userCheck = await db .collection("like") .find({ clickedUser: data.userEmail }) .toArray();
let countCheck = await db .collection("post") .find({ _id: new ObjectId(data.postId) }) .toArray();
let nowCount = countCheck[0].like;
if (userCheck.length === 0) { let increaseLike = await db.collection("like").insertOne(newLike); let increaseCount = await db.collection("post").updateOne( { _id: new ObjectId(data.postId) }, { $inc: { like: 1 } } ); return res.status(200).json("글에 좋아요를 눌렀습니다"); } else { for (let i = 0; i < userCheck.length; i++) { if (userCheck[i].postId == data.postId) { return res .status(400) .json("이미 좋아요를 클릭한 게시글입니다."); } } let increaseLike = await db.collection("like").insertOne(newLike); let increaseCount = await db.collection("post").updateOne( { _id: new ObjectId(data.postId) }, { $inc: { like: 1 } } ); return res.status(200).json("글에 좋아요를 눌렀습니다"); } } }
이렇게 서버 파일을 구성했고
"use client";
import Link from "next/link";
export default function ListItem({ result, userId }) { const increaseCount = (e) => { const listItem = e.target.closest(".list-item"); let postId = e.target.parentElement.firstChild.href.split("/")[4]; let userEmail = userId; let updateCount = Number(listItem.children[4].innerHTML) + 1;
fetch("api/post/like", { method: "POST", body: JSON.stringify({ postId: postId, userEmail: userEmail, updateCount: updateCount, }), }); };
return ( <> {result.map((item, i) => { return ( <div className="list-item" key={i}> <Link href={`/detail/${result[i]._id}`}> <h4>{item.title}</h4> </Link> <Link href={`/edit/${result[i]._id}`}>✏️</Link> <span onClick={(e) => { fetch("/api/post/delete", { method: "DELETE", body: JSON.stringify({ id: result[i]._id, author: result[i].author, }), }) .then((res) => { if (res.status == 200) { return res.json(); } else { // 서버가 에러코드 전송 시 실행할코드 } }) .then((res) => { // 성공시 실행할 코드 e.target.parentElement.style.opacity = 0; setTimeout(() => { e.target.parentElement.style.display = "none"; }, 1000); }) .catch((err) => { //인터넷 문제로 실패시 실행할코드 if (res.status == 500) { console.log(err); } }); }} > 🗑️ </span> <span onClick={increaseCount}>👍</span>
<span>{item.like}</span> <p> 1월1일</p> </div> ); })} </> ); }
// fetch(`/api/test?id=${result[i]._id}`, { // method: "DELETE", // }) // .then((res) => { // if (res.status == 200) { // return res.json(); // } else { // // 서버가 에러코드 전송 시 실행할코드 // } // }) // .then((res) => { // // 성공시 실행할 코드
// e.target.parentElement.style.opacity = 0; // setTimeout(() => { // e.target.parentElement.style.display = // "none"; // }, 1000); // }) // .catch((err) => { // //인터넷 문제로 실패시 실행할코드 // });
이렇게 ListItem 파일 작성했고
현재 한 계정으로는 한 게시글당 좋아요 1번 구현에 성공은 했습니다. 코드에서 비효율적이어서 보완해야할 부분이 있는 지 궁금합니다 ! 아니면 뭔가 에러가 발생할만한 부분이 있는지도 궁금합니다!
2023년 8월 23일 19:26 #95615
codingapple키 마스터현재 유저 이메일은 보내라고하지말고 getServerSession() 같은걸로 출력해서 씁시다 유저가 클릭한 document 전부 가져오라는거보다 해당글id와 유저이메일이 둘 다 수록된 document만 검색해보면 전부 가져올 필요 없을듯요
-
글쓴이글
2 글 보임 - 1 에서 2 까지 (총 2 중에서)
- 답변은 로그인 후 가능합니다.