20220727_TIL_개인 과제 완성, CS스터디 발표 준비

codeing999·2022년 7월 27일
0

TIL/WIL

목록 보기
10/22

오늘 한 일 및 회고

@ CS스터디 발표자료 만듬. 비트와 바이트가 다양하게 쓰인다는 내용인데 너무 적은 분량이 발표 범위라서 비트랑 바이트가 쓰이는 것들 생각나는 대로 찾아서 발표 자료 만들었다.
@ 개인과제 일단 기능은 완성한 것 같다. 이제 내일 AWS 배포만 하고 문제 답변만 하면 과제 끝일 것 같다. 제출할 땐 주석을 다 지우고 제출해야할 것 같아서 일단 여기다가 코드 다 복사해두었다. 나중에 시간이 난다면 주석에 적어놓은 것들을 더 제대로 정리해야겠다.

CS스터디 발표 자료

비트 모아 데이터

개인 과제 (express.js로 CRUD 구현)

과제 요구사항

  1. 전체 게시글 목록 조회 API
    • 제목, 작성자명, 작성 날짜를 조회하기
    • 작성 날짜 기준으로 내림차순 정렬하기
  2. 게시글 작성 API
    • 제목, 작성자명, 비밀번호, 작성 내용을 입력하기
  3. 게시글 조회 API
    • 제목, 작성자명, 작성 날짜, 작성 내용을 조회하기
      (검색 기능이 아닙니다. 간단한 게시글 조회만 구현해주세요.)
  4. 게시글 수정 API
    • API를 호출할 때 입력된 비밀번호를 비교하여 동일할 때만 글이 수정되게 하기
  5. 게시글 삭제 API
    • API를 호출할 때 입력된 비밀번호를 비교하여 동일할 때만 글이 삭제되게 하기
  6. 댓글 목록 조회
    • 조회하는 게시글에 작성된 모든 댓글을 목록 형식으로 볼 수 있도록 하기
    • 작성 날짜 기준으로 내림차순 정렬하기
  7. 댓글 작성
    • 댓글 내용을 비워둔 채 댓글 작성 API를 호출하면 "댓글 내용을 입력해주세요" 라는 메세지를 return하기
    • 댓글 내용을 입력하고 댓글 작성 API를 호출한 경우 작성한 댓글을 추가하기
  8. 댓글 수정
    • 댓글 내용을 비워둔 채 댓글 수정 API를 호출하면 "댓글 내용을 입력해주세요" 라는 메세지를 return하기
    • 댓글 내용을 입력하고 댓글 수정 API를 호출한 경우 작성한 댓글을 수정하기
  9. 댓글 삭제
    • 원하는 댓글을 삭제하기

데이터베이스 설계

Note

nametypelimitnullabledescription
noteIdObjectIdUnique:truefalse게시글ID
authorstringMin:1 Max:20 Unique:falsefalse글 작성자
pwstringMin:1 Max:30 Unique:falsefalse글 비밀번호
titlestringMin:1 Max:50 Unique:falsefalse글 제목
contentstringMin:1 Max:1000 Unique:falsefalse글 내용
createdAtDatedefault:today Unique:falsefalse글 작성 날짜

Comment

nametypelimitnullabledescription
noteIdObjectIdFK
commentIdObjectIdUnique:truefalse댓글ID
authorstringMin:1 Max:20 Unique:falsefalse댓글 작성자
contentstringMin:1 Max:200 Unique:falsefalse댓글 내용
createdAtDatedefault:today Unique:falsefalse댓글 작성 날짜

API 설계

Note

Method, URLDescriptionMethodrequestresponse
POST /note게시글 작성
GET /note/:noteId게시글 조회, 댓글 목록 조회
GET /note전체 게시글 목록 조회, 댓글 목록 조회
PUT /note/:noteId게시글 수정
DELETE /note/noteId게시글 삭제

Comment

Method, URLDescriptionMethodrequestresponse
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 파일들. 만약 만든다면.

코드

routes/comments.js

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  a = req.body;  //get도 바디값 받아올 수 있긴하네 그냥 되긴되는데 안쓰기록 약속한걸수도. 알아보니까 express.js에선 되는데 프론트엔드에서 어차피 안된다고 함.
    //console.log(a);
    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}); //, {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 author = req.body.author; //하나씩 받아올 때 이런식. get을 제외한 포스트, 풋, 딜리트 이런애들은 바디를 가져올수가있다. 
    //const {author} = req.body; //이런식으로 {}로 감싸서 해도 됨.
    const { noteId, author, pw, title, content} = req.body; //한꺼번에 가져오기.
    const note = await Note.find({ noteId });  //find 함수가 promis를 반환해서. await 쓸수있게 위에 async 써야함.
    if (note.length) {   //note에 아무것도 안담겨오면  길이가 0일 때 = 즉 못찾았을 때인데. 이건 찾앗을 경우.
        return res.status(400).json({ success: false, errorMessage: "이미 있는 데이터입니다." });    //여기서 리턴한 이유는 실패시 밑에꺼 실행안하기위함. else쓰면 더 길어지니까 return해도 아무 상관없을 때는 짧게 코딩하는거.
    }   //실패할 때도 200 ok.를 보내버리는데 400으로 보내기위해 저사이에 .status(400) 추가. 
    const createnote = await Note.create({ noteId, author, pw, title, content, createdAt:Date.now() }); //create는 모델을 만들고 insert까지 해주는 함수.
    
    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} ); //promise객체로 내보니지기때문에 await 써야함.
    // 비밀번호는 보여주면 안되기때문에 slelect에서 pw뺐고. 날짜순 내림차순이라서 sort 써서 -1 넣음. 
    res.json({
        note // note : note 와 같은 구문. note, 콤마는 넣어도 되는건가.
        //"title" : note[0].title


    });
});

router.put("/:noteId", async (req, res) => {    //많이 바꾸면 put 적게 바꾸면 patch.
    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}); //, {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;

schemas/comment.js

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,
        //default : Date.now()    //이건 서버 킬 때 초기시간으로 고정되버려서 나중에 db에 넣을 때 date.now 호출해야함.
    }
});

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); //모델 이름은 Note로 해서 export. 이걸 routes/posts.js에서 가져다 쓰게할 거.
profile
코딩 공부 ing..

0개의 댓글