오늘 한 일 및 회고
@ CS스터디 발표자료 만듬. 비트와 바이트가 다양하게 쓰인다는 내용인데 너무 적은 분량이 발표 범위라서 비트랑 바이트가 쓰이는 것들 생각나는 대로 찾아서 발표 자료 만들었다.
@ 개인과제 일단 기능은 완성한 것 같다. 이제 내일 AWS 배포만 하고 문제 답변만 하면 과제 끝일 것 같다. 제출할 땐 주석을 다 지우고 제출해야할 것 같아서 일단 여기다가 코드 다 복사해두었다. 나중에 시간이 난다면 주석에 적어놓은 것들을 더 제대로 정리해야겠다.
CS스터디 발표 자료
비트 모아 데이터
개인 과제 (express.js로 CRUD 구현)
과제 요구사항
- 전체 게시글 목록 조회 API
- 제목, 작성자명, 작성 날짜를 조회하기
- 작성 날짜 기준으로 내림차순 정렬하기
- 게시글 작성 API
- 제목, 작성자명, 비밀번호, 작성 내용을 입력하기
- 게시글 조회 API
- 제목, 작성자명, 작성 날짜, 작성 내용을 조회하기
(검색 기능이 아닙니다. 간단한 게시글 조회만 구현해주세요.)
- 게시글 수정 API
- API를 호출할 때 입력된 비밀번호를 비교하여 동일할 때만 글이 수정되게 하기
- 게시글 삭제 API
- API를 호출할 때 입력된 비밀번호를 비교하여 동일할 때만 글이 삭제되게 하기
- 댓글 목록 조회
- 조회하는 게시글에 작성된 모든 댓글을 목록 형식으로 볼 수 있도록 하기
- 작성 날짜 기준으로 내림차순 정렬하기
- 댓글 작성
- 댓글 내용을 비워둔 채 댓글 작성 API를 호출하면 "댓글 내용을 입력해주세요" 라는 메세지를 return하기
- 댓글 내용을 입력하고 댓글 작성 API를 호출한 경우 작성한 댓글을 추가하기
- 댓글 수정
- 댓글 내용을 비워둔 채 댓글 수정 API를 호출하면 "댓글 내용을 입력해주세요" 라는 메세지를 return하기
- 댓글 내용을 입력하고 댓글 수정 API를 호출한 경우 작성한 댓글을 수정하기
- 댓글 삭제
데이터베이스 설계
Note
name | type | limit | nullable | description |
---|
noteId | ObjectId | Unique:true | false | 게시글ID |
author | string | Min:1 Max:20 Unique:false | false | 글 작성자 |
pw | string | Min:1 Max:30 Unique:false | false | 글 비밀번호 |
title | string | Min:1 Max:50 Unique:false | false | 글 제목 |
content | string | Min:1 Max:1000 Unique:false | false | 글 내용 |
createdAt | Date | default:today Unique:false | false | 글 작성 날짜 |
name | type | limit | nullable | description |
---|
noteId | ObjectId | | | FK |
commentId | ObjectId | Unique:true | false | 댓글ID |
author | string | Min:1 Max:20 Unique:false | false | 댓글 작성자 |
content | string | Min:1 Max:200 Unique:false | false | 댓글 내용 |
createdAt | Date | default:today Unique:false | false | 댓글 작성 날짜 |
API 설계
Note
Method, URL | Description | Method | request | response |
---|
POST /note | 게시글 작성 | | | |
GET /note/:noteId | 게시글 조회, 댓글 목록 조회 | | | |
GET /note | 전체 게시글 목록 조회, 댓글 목록 조회 | | | |
PUT /note/:noteId | 게시글 수정 | | | |
DELETE /note/noteId | 게시글 삭제 | | | |
Method, URL | Description | Method | request | response |
---|
POST /comment/:noteId | 댓글 작성 | | | |
GET /comment/:noteId | 댓글 목록 조회 | | | |
PUT /comment/:noteId/:commentId | 댓글 수정 | | | |
DELETE /comment/:noteId/:commentId | 댓글 삭제 | | | |
디렉토리 구조
.
├── app.js //서버 열기
├── routes
│ ├── index.js //이건 왜 만들라고 한건지 모르겠음.
│ ├── comments.js //댓글 관련 미들웨어
│ └── posts.js //글 관련 미들웨어
├── schemas
│ ├── index.js //몽고DB랑 연결 담당
│ ├── comment.js //코멘트 테이블 스키마 작성
│ └── post.js //노트 테이블 스키마 작성
└── static //html, css 파일들. 만약 만든다면.
코드
const express = require("express");
const Comment = require("../schemas/comment.js");
const router = express.Router();
router.post("/", async (req, res) => {
const { noteId, commentId, author, content, createdAt } = req.body;
const comment = await Comment.find( {noteId, commentId});
if (comment.length) {
return res.status(400).json( { success : false, erroMessage: "이미 있는 데이터입니다."});
}
const createcomment = await Comment.create( { noteId, commentId, author, content, createdAt});
res.json({ comment : createcomment});
});
router.get("/:noteId", async (req, res)=> {
const { noteId } = req.params;
const comment = await Comment.find( {noteId} ).sort( {createdAt : -1});
res.json({
comment,
});
});
router.put("/:noteId/:commentId", async (req, res)=>{
const { noteId, commentId } = req.params;
const { content} = req.body;
const comment = await Comment.find({ noteId, commentId });
console.log(noteId, commentId, content)
if (comment.length) {
if (content.length){
const putcomment = await Comment.findOneAndUpdate({ noteId:noteId, commentId:commentId}, {content:content }, {new : true});
res.json({ comment: putcomment });
} else{
res.send("댓글 내용을 입력해주세요");
}
}else {
res.send("없는 데이터입니다.");
}
});
router.delete("/:noteId/:commentId", async (req, res)=>{
const { noteId, commentId } = req.params;
const comment = await Comment.find({ noteId, commentId });
if (comment.length) {
const deletecomment = await Comment.findOneAndDelete( {noteId:noteId, commentId:commentId});
res.json({ comment: deletecomment });
}else {
res.send("없는 데이터입니다.");
}
});
module.exports = router;
routes/posts.js
const express = require("express");
const Note = require("../schemas/post.js");
const router = express.Router();
router.post("/", async (req, res) => {
const { noteId, author, pw, title, content} = req.body;
const note = await Note.find({ noteId });
if (note.length) {
return res.status(400).json({ success: false, errorMessage: "이미 있는 데이터입니다." });
}
const createnote = await Note.create({ noteId, author, pw, title, content, createdAt:Date.now() });
res.json({ note: createnote });
});
router.get("/:noteId", async (req, res) => {
const { noteId } = req.params;
const [note] = await Note.find({ noteId: Number(noteId) }).select('-pw -__v -_id -noteId');
res.json({
note
});
});
router.get("/", async (req, res) => {
const note = await Note.find().select( '-pw -content -__v -_id -noteId' ).sort( {createdAt : -1} );
res.json({
note
});
});
router.put("/:noteId", async (req, res) => {
const { noteId } = req.params;
const { pw, title, content} = req.body;
const note = await Note.find({ noteId, pw });
if (note.length) {
const putnote = await Note.findOneAndUpdate({ noteId:noteId}, {title:title, content:content }, {new : true});
res.json({ note: putnote });
}else {
res.send("없는 데이터 입니다.");
}
});
router.delete("/:noteId", async (req, res) => {
const { noteId } = req.params;
const { pw} = req.body;
const note = await Note.find({ noteId, pw });
if (note.length) {
const deletenote = await Note.findOneAndDelete( {noteId:noteId});
res.json({ note: deletenote });
}else {
res.send("없는 데이터입니다.");
}
});
module.exports = router;
const mongoose = require("mongoose");
const commentSchema = new mongoose.Schema({
noteId : {
type : Number,
required : true,
unique : false
},
commentId : {
type : Number,
required : true,
unique : false
},
author: {
type: String,
required: true,
unique: false
},
content: {
type: String,
required: true,
unique: false
},
createdAt: {
type: Date,
required: true,
unique: false,
}
});
module.exports = mongoose.model("Comment", commentSchema);
schemas/index.js
const mongoose = require("mongoose");
const connect = () => {
mongoose
.connect("mongodb://localhost:27017/basic_web")
.catch(err => console.log(err));
};
mongoose.connection.on("error", err => {
console.error("몽고디비 연결 에러", err);
});
module.exports = connect;
schemas/post.js
const mongoose = require("mongoose");
const noteSchema = new mongoose.Schema({
noteId: {
type: Number,
required: true,
unique: true
},
author: {
type: String,
required: true,
unique: false
},
pw: {
type: String,
required: true,
unique: false
},
title: {
type:String,
required: true,
unique: false
},
content: {
type: String,
required: true,
unique: false
},
createdAt: {
type: Date,
required: true,
unique: false,
}
});
module.exports = mongoose.model("Note", noteSchema);