node.js

게시판 만들기 (완성버전)

늘곰's 2023. 8. 29. 19:19

게시판 만들기의 완성 버전

기존의 코드에서 지저분했던 코드와 주석들을 수정하고 TRY CATCH 를 사용하여 이전보다 깔끔하게 코드를 만듬

 

최상위 app.js

import express from 'express';
import connect from './schmas/index.js'
//import indexRouter from './routes/index.js'
import postRouter from './routes/post.router.js'
import commnetRouter from './routes/comments.router.js'
const app = express();
const PORT = 3000;

connect();




// Express에서 req.body에 접근하여 body 데이터를 사용할 수 있도록 설정합니다.
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

const router = express.Router();

router.get('/', (req, res) => {
  return res.json({ message: 'Hi!' });
});

app.use('/api', [router, postRouter,commnetRouter]);

app.listen(PORT, () => {
  console.log(PORT, '포트로 서버가 열렸어요!');
});

스키마 폴더 index.js

 

// schemas/index.js

import mongoose from 'mongoose';

const connect = () => {
  mongoose
    .connect(
      // 빨간색으로 표시된 부분은 대여한 ID, Password, 주소에 맞게끔 수정해주세요!
      'mongodb+srv://sparta:test@cluster0.azratxu.mongodb.net/?retryWrites=true&w=majority',
      {
        dbName: 'notice_board', // notice_board 데이터베이스명을 사용합니다.
      },
    )
    .then(() => console.log('MongoDB 연결에 성공하였습니다.'))
    .catch((err) => console.log(`MongoDB 연결에 실패하였습니다. ${err}`));
};

mongoose.connection.on('error', (err) => {
  console.error('MongoDB 연결 에러', err);
});

export default connect;

스키마 폴더 post

// schemas/post.schema.js

import mongoose from "mongoose";

const postSchema = new mongoose.Schema({
  user: {
    type: String,
    required: true, // 필수요소
  },
  password: {
    type: String,
    required: true, // 필수요소
  },
  title: {
    type : String,
    required : true, // 필수요소
  },
  content: {
    type : String,
    required : true, // 필수요소
  },
  createdAt: {
    type: Date, // createAt 필드는 Date 타입을 가집니다.
    required: true, 
  },
});


export default mongoose.model("Schemapost", postSchema);

 

스키마 폴더 comment

// schemas/comment.schema.js

import mongoose from "mongoose";


const commentSchema = new mongoose.Schema({
  postId: {
    type: String,
    required: true, // 필수요소
  },
  user: {
    type: String,
    required: true, // 필수요소
  },
  password: {
    type: String,
    required: true, // 필수요소
  },
  content: {
    type : String,
    required : true, // 필수요소
  },
  createdAt: {
    type: Date, // createAt 필드는 Date 타입을 가집니다.
    required: false, 
  },
});


export default mongoose.model("Schemacomment", commentSchema);

라우터 폴더 post

 

import express from 'express';
import Schemapost from '../schmas/post.schema.js'
const router = express.Router();




/* 게시판 등록  API*/

router.post('/posts', async(req,res, next) =>{
try{
    const {title, user, password , content } = req.body
    
    const newPost = new Schemapost({
        user,
        password,
        title,
        content,
        createdAt : new Date()

    })
    await newPost.save();
    res.status(201).json({message:'개시글을 생성하였습니다'})
}catch{
    console.error(err);
    return res.status(400).json({message : '데이터 형식이 올바르지 않습니다.'})
}

    
}) 


/* 게시판 목록 조회 */
router.get('/posts',  async(req, res, next) => {

    const cheakpost = await Schemapost.find().sort({createdAt : -1}).exec();


    const mapCheakpost = cheakpost.map(post =>({
        postId :post._id,  // _id 를 postId로 변경
        user: post.user,
        title : post.title,
        createdAt: post.createdAt
    }));


    return res.status(200).json({ mapCheakpost });

  });


/* 게시글 상세 조회 */
router.get('/posts/:_postId', async(req, res, next) => {
try{
    const {_postId} = req.params;

    const cheak1post = await Schemapost.findById(_postId).exec();
    
    const mapCheak1post = {
        postId :cheak1post._id,
        user: cheak1post.user,
        content : cheak1post.content,
        createdAt: cheak1post.createdAt
    }

    return res.status(201).json({mapCheak1post});

} catch{
    console.error(err);
    return res.status(400).json({message : '데이터 형식이 올바르지 않습니다.'})
}

});

/* 게시글 수정 */
router.put('/posts/:_postId', async(req, res, next) => {
    try{
        const {_postId} = req.params;
        const {password , title, content} = req.body;
    
    
        const editpost = await Schemapost.findById(_postId).exec();
    
        if(!editpost) {
            return res.status(404).json({message : '게시글 조회에 실패하였습니다.'})
        }
    
        if(editpost.password !== password){
            return res.status(400).json({message : '비밀번호가 맞지 않습니다.'})
        }
    
        editpost.title  = title;
    
        editpost.content = content;
    
    
        await editpost.save();
        
    
        return res.status(200).json({massege: '게시글이 수정되었습니다.'})
    } catch{
               
        console.error(err);
        return res.status(400).json({message : '데이터 형식이 올바르지 않습니다.'})

            

    }
    



});

/* 게시글 삭제 */
router.delete('/posts/:_postId', async(req,res,next)=>{
    try{
        const {_postId} = req.params;
        const {password} = req.body;
    
        const  deletepost = await Schemapost.findById(_postId).exec();

        if(!deletepost){
            return res.status(404).json({message : '게시글 조회에 실패하였습니다.'})
        }

    
        await deletepost.deleteOne({password: _postId});
        
        if(deletepost.password !== password){
            return res.status(400).json({message : '비밀번호가 맞지 않습니다.'})
        }
    
        return res.status(200).json({message : '게시글을 삭제하였습니다.'});
    
    } catch{
        console.error(err);
        return res.status(400).json({message : '데이터 형식이 올바르지 않습니다.'})
        
    }
    


});





export default router;

라우터 폴더 comment

 

import express from 'express';
import schemaPost from '../schmas/post.schema.js'
import schemaComment from '../schmas/comments.schema.js'


//express.js 라우터 생성

const router = express.Router();



/* 댓글 생성 API */

router.post('/post/:_postId/comments', async(req,res,next) =>{
try{
    const {_postId} =req.params
    const { password, user, content } = req.body

    if(!content){
        return res.status(400).json({ Message : '댓글 내용을 입력해주세요'})
    }


    const newComment = new schemaComment({
        postId : _postId,
        user,
        password,
        content,
        createdAt : new Date()

    })


    await newComment.save();


    res.status(201).json({message:'댓글을 생성하였습니다.'})
}catch{
    console.error(err);
    return res.status(400).json({message : '데이터 형식이 올바르지 않습니다.'})  
}

});


/* 댓글 목록 조회 */

router.get('/post/:_postId/comments', async(req, res, next) =>{
    try{

        const cheakcomment = await schemaComment.find().sort({createdAt : -1}).exec(); 


        const mapCheakcomment = cheakcomment.map(comment =>({
            return:{
                commentId : comment._id,
                user: comment.user,
                content : comment.content,
                createdAt: comment.createdAt 
            }

        }));
        
        return res.status(200).json({ mapCheakcomment });
    }catch{
        console.error(err);
        return res.status(400).send({message : '데이터 형식이 올바르지 않습니다.'})  
    }


});



/* 댓글 수정 */

router.put('/posts/:_postId/comments/:_commentId', async(req,res,next)=>{
    try{
        const {_commentId} = req.params;
        const {password , content} = req.body
        
        const editcomment = await schemaComment.findById(_commentId).exec();
    
        if(!content){
            return res.status(400).json({ Message : '댓글 내용을 입력해주세요'})
        }
        if(!_commentId){
            return res.status(404).json({ Message : '댓글 조회에 실패하였습니다.'})
        }
        if(editcomment.password !== password){
            return res.status(400).json({ Message : '비밀번호가 맞지 않습니다.'})
        }
    
    
        editcomment.content = content;
    
        await editcomment.save();
        
        return res.status(200).json({massege: '댓글이 수정되었습니다.'})
    }catch{
        console.error(err);
        return res.status(400).send({message : '데이터 형식이 올바르지 않습니다.'}) 
    }
   

});



/* 댓글 삭제 */

router.delete('/posts/:_postId/comments/:_commentId', async(req,res,next) => {
try{
    const {_commentId} = req.params;
    const {password} = req.body;


    const  deletecomment = await schemaComment.findById(_commentId).exec();

    if(!_commentId){
        return res.status(404).json({message : '댓글 조회에 실패하였습니다.'})
    }
    if(deletecomment.password !== password){
        return res.status(400).json({ Message : '비밀번호가 맞지 않습니다.'})
    }


    await deletecomment.deleteOne({password: _commentId});
    

    return res.status(200).json({message : '댓글을 삭제하였습니다.'});

}catch{
    console.error(err);
        return res.status(400).send({message : '데이터 형식이 올바르지 않습니다.'}) 
}

});









export default router;

 

마지막으로

기능은 제대로 작동하지만 아직 수정할 부분이 조금씩 남아있음
수정이 되면 수정된 사항을 글로 쓸 예정