728x90
Node.js 숙련 주차 개인 과제_3
📌 게시글 API
📌 Comment 모델 생성(Terminal)
npx sequelize model:generate --name Comment --attributes comment:string,userId:integer,postId:integer
Id → commentId 수정
userId를 외래키로 user모델과 연결
📄 /models/comment.js
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class Comment extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
models.Comment.belongsTo(models.Post, {foreignKey: "postId"})
models.Comment.belongsTo(models.User, {foreignKey: "userId"})
}
}
Comment.init({
commentId: {
primaryKey: true,
type: DataTypes.INTEGER,
},
comment: DataTypes.STRING,
userId: DataTypes.INTEGER,
postId: DataTypes.INTEGER
}, {
sequelize,
modelName: 'Comment',
});
return Comment;
};
📄 /migrations/숫자-create-comment.js 파일
'use strict';
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable('Comments', {
commentId: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
comment: {
type: Sequelize.STRING
},
userId: {
type: Sequelize.INTEGER
},
postId: {
type: Sequelize.INTEGER
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
async down(queryInterface, Sequelize) {
await queryInterface.dropTable('Comments');
}
};
📌 테이블 생성하기(Terminal)
npx sequelize db:migrate
댓글 생성
📄 app.js
// 댓글 생성
router.post("/comments/:postId", authMiddleware, async(req,res) => {
try {
const { userId } = res.locals.user;
const { postId } = req.params;
const { comment } = req.body;
if(Object.keys(req.body).length === 0){
res.status(412).send({
errorMessage: "데이터 형식이 올바르지 않습니다."
});
return;
}
await Comment.create({ comment, postId, userId })
res.status(201).send({ message: "댓글을 작성하였습니다." });
} catch(error) {
res.status(400).json({
errorMessage: "댓글 작성에 실패하였습니다."
});
}
})
📌 ThunderClient
[POST] http://localhost:8080/api/comments/4
headers
userId : 1
Authorization : Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEsImlhdCI6MTY3MTc2MzEzMCwiZXhwIjoxNjcxODQ5NTMwfQ.x1svr852XGvP14IcSb8xlJoGIB6r1ssl7bHiM8GF-QI
userId : 2
Authorization : Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjIsImlhdCI6MTY3MTc2MzEwOCwiZXhwIjoxNjcxODQ5NTA4fQ.W0TahSG3kZEjym160TN-Hu73jMxVBZ38SphqEtFAYpg
body - json
댓글 테이블(Comments Table)
댓글 목록 조회
📄 app.js
// 댓글 목록 조회
router.get("/comments/:postId", async(req,res) => {
try {
const { postId } = req.params;
const comment = await Comment.findAll({
where: { postId },
include: [{
model: User,
required: false,
attributes: ['nickname'],
}]
});
res.json({"data": comment});
} catch(error) {
res.status(400).json({
errorMessage: "댓글 조회에 실패하였습니다."
});
}
})
📌 ThunderClient
[GET] http://localhost:8080/api/comments/4
댓글 수정
📄 app.js
// 댓글 수정
router.put("/comments/:commentId", authMiddleware, async(req,res) => {
try {
const { userId } = res.locals.user;
const { commentId } = req.params;
const { comment } = req.body;
console.log(commentId, userId);
if(!comment){
res.status(412).send({
errorMessage: "데이터 형식이 올바르지 않습니다."
});
return;
}
const existCmt = await Comment.findByPk(commentId);
if(!existCmt) {
res.status(404).send({
errorMessage: "댓글이 존재하지 않습니다."
});
return;
}
const findcmt = await Comment.findOne({
where: { commentId, userId }
});
if(!findcmt){
res.status(400).send({
errorMessage: "댓글 수정이 정상적으로 처리되지 않았습니다."
});
return;
}
findcmt.comment = comment;
await findcmt.save();
res.status(200).send({ message: "댓글을 수정하였습니다." });
} catch(error) {
res.status(400).json({
errorMessage: "댓글 수정에 실패하였습니다."
});
}
})
📌 ThunderClient
[PUT] http://localhost:8080/api/comments/5
headers
userId : 2
Authorization : Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjIsImlhdCI6MTY3MTc2MzEwOCwiZXhwIjoxNjcxODQ5NTA4fQ.W0TahSG3kZEjym160TN-Hu73jMxVBZ38SphqEtFAYpg
body - json & 수정 완료!
댓글 삭제
📄 app.js
// 댓글 삭제
router.delete("/comments/:commentId", authMiddleware, async(req,res) => {
try {
const { userId } = res.locals.user;
const { commentId } = req.params;
const existCmt = await Comment.findByPk(commentId);
if(!existCmt) {
res.status(404).send({
errorMessage: "댓글이 존재하지 않습니다."
});
return;
}
const findcmt = await Comment.findOne({
where: { commentId, userId }
});
if(!findcmt){
res.status(400).send({
errorMessage: "댓글 삭제가 정상적으로 처리되지 않았습니다."
});
return;
}
await findcmt.destroy();
res.status(200).send({ message: "댓글을 삭제하였습니다." })
} catch(error) {
res.status(400).json({
errorMessage: "댓글 삭제에 실패하였습니다."
});
}
})
📌 ThunderClient
[DELETE] http://localhost:8080/api/comments/7
headers
userId : 1
Authorization : Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEsImlhdCI6MTY3MTc2MzEzMCwiZXhwIjoxNjcxODQ5NTMwfQ.x1svr852XGvP14IcSb8xlJoGIB6r1ssl7bHiM8GF-QI
'JavaScript' 카테고리의 다른 글
Node 숙련 개인과제 ER다이어그램 (0) | 2022.12.26 |
---|---|
Node.js 심화 1주차_1 (0) | 2022.12.26 |
Node.js 숙련 주차 개인 과제_2 (1) | 2022.12.22 |
Node.js 숙련 주차 개인 과제_1 (0) | 2022.12.22 |
Node.js 숙련 1주차_6 (1) | 2022.12.21 |