Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

221008 commit 시작 #1

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
195 changes: 64 additions & 131 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
"express-session": "^1.17.3",
"mongoose": "^6.5.1",
"morgan": "^1.10.0",
"node-fetch": "^3.2.10",
"node-fetch": "^2.6.6",
"pug": "^3.0.2"
},
"devDependencies": {
Expand Down
83 changes: 83 additions & 0 deletions src/client/js/commentSection.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import fetch from "node-fetch";

const questionContainer = document.getElementById("questionContainer");
const form = document.getElementById("commentForm");
const textarea = form.querySelector("textarea");
const deleteComments = document.querySelectorAll(".delete_comment");

const addComment = (text, id) => {
const commentContainer = document.querySelector(".question_garden_grid");
const commentList = document.createElement("i");
commentList.dataset.id = id;
commentList.classList.add("question_garden_comment");
const icon = document.createElement("i");
icon.className = "fas fa-comment";
const span = document.createElement("span");
span.innerText = ` ${text}`;
const button = document.createElement("button");
button.innerText = " ❌";
commentList.appendChild(icon);
commentList.appendChild(span);
commentList.appendChild(button);
commentContainer.appendChild(commentList); //prepend는 위에 담
button.addEventListener("click", handleDelete);
} //새로고침하기 전까지만 html에 가짜 댓글을 달게 해줌. 새로고침시 이는 사라지고 DB속 내용으로 추가됨

const deleteComment = (event) => {
const commentContainer = document.querySelector(".question_garden_grid");
const commentList = event.target.parentNode;
commentContainer.removeChild(commentList);
}
const handleSubmit = async (event) => {
event.preventDefault();
const text =textarea.value;
const questionId = questionContainer.dataset.id;
if(text === ""){
return; //댓글이 공백일때 전송 x
}
const response = await fetch(`/qna/${questionId}/comment`,{
method:"POST",
headers: {
"Content-Type": "application/json", //string을 보내주지만 json string이라고 알려주는 표시
},
body: JSON.stringify({text}), //req.body 속 내용을 전달하는 역할을 함
});
if(response.status === 201){
const { newCommentId } = await response.json();
textarea.value = "";
addComment(text,newCommentId);
}
//window.location.reload(); //자동 새로고침 ! -> 부하걸리는 작업이라 변환할 거임
};

const handleDelete = async (event) =>{
const commentList = event.target.parentNode;
const commentId = commentList.dataset.id;
const questionId = questionContainer.dataset.id;
const response = await fetch(`/qna/${commentId}/commentdelete`,{
method: "DELETE",
headers: {
"Content-Type" : "application/json"
},
body : JSON.stringify({
questionId,
})
});
if(response.status === 201) {
deleteComment(event);
}
if(response.status === 403) {
alert("댓글 주인이 아닙니다.");
}
}


if (form){
form.addEventListener("submit", handleSubmit);
}
for (let i =0; i< deleteComments.length; i++)
{
deleteComments[i].addEventListener("click", handleDelete);
}


27 changes: 27 additions & 0 deletions src/client/scss/screens/garden.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
.question_garden_grid{
gap: 5px;
display: flex;
flex-direction:column;
max-width: 500px;
width: 100%;
margin:0 auto;
margin-top:20px;
.question_garden_comment{
padding: 5px;
text-align: left;
border-radius: 9999px;
background-color: white;
color: black;
margin-bottom:10px;

}
}
.question_garden_comment{
button{
border: 1px solid rgba(0,0,0,0);
background-color: rgba(0,0,0,0);
padding: 5px;
border-radius:10px;
box-shadow: 0px 0px 2px 2px rgb(20, 20, 130);
}
}
3 changes: 2 additions & 1 deletion src/client/scss/styles.scss
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
@import "./screens/home.scss";
@import "./screens/search.scss";
@import "./screens/myProfile.scss";
@import "./screens/garden.scss";

//Defaults
a {
Expand All @@ -34,4 +35,4 @@ main {
max-width: 1200px;
width: 100%;
margin: 50px auto;
}
}
59 changes: 57 additions & 2 deletions src/controllers/qnaController.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import req from "express/lib/request";
import res from "express/lib/response";
import Question from "../models/Question";
import User from "../models/User";
import Comment from "../models/Comment";

export const mainQ = async (req, res) => {
const { keyword } = req.query;
Expand All @@ -20,7 +21,7 @@ export const mainQ = async (req, res) => {

export const seeQ = async (req, res) => {
const { id } = req.params;
const question = await Question.findById(id).populate("owner");
const question = await Question.findById(id).populate("owner").populate("comments");

if (!question) {
return res.status(404).render("404", { pageTitle: "Question not found." });
Expand Down Expand Up @@ -144,4 +145,58 @@ export const deleteQ = async (req, res) => {
//console.log(question);

return res.redirect("/qna");
};
};

export const createComment = async (req, res) => {
// console.log(req.params); //질문의 id
// console.log(req.body); //사용자의 댓글 내용
// console.log(req.body.text);
// console.log(req.session.user); //사용자의 정보
const {
session:{user},
body:{text},
params: {id},
} = req;
const question = await Question.findById(id);
if(!question){
return res.sendStatus(404);
}
const commentUser = await User.findById(user._id);
const comment = await Comment.create({
text,
owner: user._id,
questions: id,
});

question.comments.push(comment._id);
commentUser.comments.push(comment._id);
commentUser.save();
question.save();
req.session.user = commentUser;

console.log(user, text, id);
res.status(201).json({
newCommentId: comment._id,
});
}

export const deleteComment = async(req,res) => {
const { params: { id },
body: { questionId },
session:{ user }
} = req;
const question = await Question.findById(questionId);
const commentUser = await User.findById(user._id);
if(user.comments.indexOf(id) < 0) {
req.flash("info", "Not authorized");
return res.sendStatus(403);
}
commentUser.comments.splice(commentUser.comments.indexOf(id), 1);
question.comments.splice(question.comments.indexOf(id), 1);

await question.save();
await commentUser.save();
await Comment.findByIdAndDelete(id);

return res.sendStatus(201);
}
1 change: 1 addition & 0 deletions src/init.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import "./db";
import "./models/User";
import "./models/Locker";
import "./models/Question";
import "./models/Comment";

import app from "./server";

Expand Down
12 changes: 12 additions & 0 deletions src/models/Comment.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import mongoose from "mongoose";

const commentSchema = new mongoose.Schema({
text: {type:String, required:true},
owner: { type: mongoose.Schema.Types.ObjectId, required: true, ref: "User" },
questions: { type: mongoose.Schema.Types.ObjectId, required: true, ref: "Question" },
createdAt: { type: Date, required: true, default: Date.now },
})

const Comment = mongoose.model("Comment", commentSchema);

export default Comment;
1 change: 1 addition & 0 deletions src/models/Question.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const questionSchema = new mongoose.Schema({
views: { type: Number, default: 0, required: true },
},
hashtags: [{ type: String }],
comments: [{type:mongoose.Schema.Types.ObjectId, required:true, ref:"Comment"}],
owner: { type: mongoose.Schema.Types.ObjectId, required: true, ref: "User" },
});
// 우리가 제공해주는 데이터 : number, createdAt, views
Expand Down
3 changes: 2 additions & 1 deletion src/models/User.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ const userSchema = new mongoose.Schema({
password: {type: String, required: true, trim:true },
phoneNumber: {type: Number, required: true, trim:true, unique : true },
questions: [{ type: mongoose.Schema.Types.ObjectId, ref: "Question" }],
locker: [{ type: mongoose.Schema.Types.ObjectId, ref: "Locker" }],
locker: [{ type: mongoose.Schema.Types.ObjectId, ref: "Locker" }],
comments: [{type:mongoose.Schema.Types.ObjectId, ref:"Comment"}],

/*
export const myProfile = async (req, res) => {
Expand Down
11 changes: 10 additions & 1 deletion src/routers/qnaRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { mainQ,
seeQ,
getUploadQ, postUploadQ,
getEditQ, postEditQ,
deleteQ, } from "../controllers/qnaController";
deleteQ, createComment,deleteComment } from "../controllers/qnaController";
import { protectorMiddleware } from "../middlewares"

const qnaRouter = express.Router();
Expand All @@ -29,5 +29,14 @@ qnaRouter
.route("/:id([0-9a-f]{24})/delete") // 질문 삭제 페이지
.all(protectorMiddleware)
.get(deleteQ);
qnaRouter
.route("/:id([0-9a-f]{24})/comment")
.all(protectorMiddleware)
.post(createComment);
qnaRouter
.route("/:id([0-9a-f]{24})/commentdelete")
.all(protectorMiddleware)
.delete(deleteComment);


export default qnaRouter;
11 changes: 9 additions & 2 deletions src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,20 @@ app.set("view engine", "pug");
app.set("views", process.cwd() + "/src/views");

app.use(morgan("dev"));
app.use(express.urlencoded({ extended: true }));
app.use(express.urlencoded({ extended: true }));
//pug 속 input을 req.body로 server가 이해할 수 있게 전달해주는 middleware
//app.use(express.text());
//text를 보내면 backend에서 이해할 수 있도록 하는 middleware
//comment backend로 전달하는 용
app.use(express.json());
//string -> JSon화 해서 "text": "something" -> text : "something"
app.use(
session({
store: MongoStore.create({ mongoUrl: process.env.DB_URL }),
secret: process.env.COOKIE_SECRET,
resave: false,
saveUninitialized: false,
store: MongoStore.create({ mongoUrl: process.env.DB_URL }),

})
);

Expand Down
4 changes: 3 additions & 1 deletion src/views/base.pug
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,6 @@ html(lang="ko")
include partials/footer

script(src="/static/js/main.js")
script(src="https://kit.fontawesome.com/d552185620.js" crossorigin="anonymous")
script(src="https://kit.fontawesome.com/d552185620.js" crossorigin="anonymous")
if(loggedIn)
script(src="/static/js/commentSection.js")
4 changes: 4 additions & 0 deletions src/views/qna/editQ.pug
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,7 @@ block content
input(placeholder="Content", required, type="text", name="content", value=question.content)
input(placeholder="Hashtags, separated by ,", required, type="text", name="hashtags", value=question.hashtags.join())
input(value="질문 수정하기",type="submit")

div.center
div.arrow-switch
a(href="/qna") 뒤로가기 &larr;
38 changes: 29 additions & 9 deletions src/views/qna/seeQ.pug
Original file line number Diff line number Diff line change
@@ -1,15 +1,35 @@
extends ../base

block content
div
p=question.content
small=question.createdAt
div
p=question.content
small=question.createdAt

div
small Uploaded by #{question.owner.userName}
div
small Uploaded by #{question.owner.userName}

if String(question.owner.id) === String(loggedInUser._id)
if String(question.owner.id) === String(loggedInUser._id)
div.arrow-switch
a(href=`${question.id}/editq`) 수정하기 &rarr;
div.arrow-switch
a(href=`${question.id}/delete`) 삭제하기 &rarr;
div#questionContainer(data-id=question._id)
if loggedIn
div.arrow-switch
form.question__comment-form#commentForm
textarea(cols="50", rows="4", placeholder="Write a comment..")
button Add Comment
div.question_garden_grid
each comment in question.comments
i.question_garden_comment(data-id=comment.id)
i.fas.fa-comment
if String(comment.owner) === String(loggedInUser._id)
span #{comment.text}
button.delete_comment ❌
else
span #{comment.text}
div.center
div.arrow-switch
a(href=`${question.id}/editq`) 수정하기 &rarr;
div.arrow-switch
a(href=`${question.id}/delete`) 삭제하기 &rarr;
a(href="/qna") 뒤로가기 &larr;


4 changes: 4 additions & 0 deletions src/views/qna/uploadQ.pug
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,9 @@ block content
input(placeholder="Hashtags, separated by ,", required, type="text", name="hashtags")
input(value="질문 올리기", type="submit")

div.center
div.arrow-switch
a(href="/qna") 뒤로가기 &larr;

if errorMessage
span=errorMessage
Loading