node.js
게시판 만들기 몽구스에서 prisma 로 변경하기
늘곰's
2023. 9. 2. 21:28
app.js
import express from 'express';
import connect from './schmas/index.js'
import postRouter from './routes/post.router.js'
// import commnetRouter from './routes/comments.router.js'
import routes from './routes/index.js'
const app = express();
const PORT = 3000;
connect();
// const router = express.Router();
// Express에서 req.body에 접근하여 body 데이터를 사용할 수 있도록 설정합니다.
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// app.use('/api', routes.commnetRouter);
// app.use('/api',routes.postRouter);
app.use('/api', [routes.commnetRouter, routes.postRouter ]);
app.listen(PORT, () => {
console.log(PORT, '포트로 서버가 열렸어요!');
});
utils
// utils/prisma/index.js
import { PrismaClient } from '@prisma/client';
export const prisma = new PrismaClient({
// Prisma를 이용해 데이터베이스를 접근할 때, SQL을 출력해줍니다.
log: ['query', 'info', 'warn', 'error'],
// 에러 메시지를 평문이 아닌, 개발자가 읽기 쉬운 형태로 출력해줍니다.
errorFormat: 'pretty',
}); // PrismaClient 인스턴스를 생성합니다.
import express from 'express';
import { prisma } from '../utils/prisma/index.js';
const router = express.Router();
/* 게시판 등록 API*/
router.post('/posts', async(req,res, next) =>{
try{
const {title, user, password , content } = req.body
const newPost = await prisma.posts.create({
data: {
user,
password,
title,
content,
createdAt : new Date()
}
})
// res.status(201).json({newPost})
res.status(201).json({message:'개시글을 생성하였습니다'})
}catch(err){
console.error(err);
return res.status(400).json({message : '데이터 형식이 올바르지 않습니다.'})
}
});
/* 게시판 목록 조회 */
router.get('/posts', async(req, res, next) => {
const cheakpost = await prisma.posts.findMany({
select :{
postId : true, // _id 를 postId로 변경 _id
user: true,
title : true,
createdAt: true
},
orderBy: {
createdAt: 'desc', // createdAt을 내림차순으로 정렬
},
})
return res.status(200).json({ data : cheakpost });
});
/* 게시글 상세 조회 */
router.get('/posts/:postId', async(req, res, next) => {
try{
const {postId} = req.params;
//const cheak1post = await Schemapost.findById(_postId).exec();
const cheak1post = await prisma.posts.findFirst({
where: {postId: +postId},
select: {
postId :true,
user: true,
content : true,
createdAt: true,
}
})
return res.status(201).json({data : cheak1post});
} catch(err){
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 prisma.posts.findUnique({
where: {postId : +postId}
});
if(!editpost) {
return res.status(404).json({message : '게시글 조회에 실패하였습니다.'})
}
if(editpost.password !== password){
return res.status(401).json({message : '비밀번호가 일치하지 않습니다.'})
}
await prisma.posts.update({
data : {title , content},
where : {
postId : +postId,
password
}
})
return res.status(200).json({message: '게시글이 수정되었습니다.'})
} catch(err){
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;
/* postId 찾기 */
const deletepost = await prisma.posts.findUnique({
where :{
postId : +postId,
password
}
})
/* 조건 */
if(!deletepost){
return res.status(404).json({message : '게시글 조회에 실패하였습니다.'})
}
if(deletepost.password !== password){
return res.status(400).json({message : '비밀번호가 맞지 않습니다.'})
}
/* 조건을 통과하면 게시글 삭제 */
await prisma.posts.delete({
where: {
postId : +postId,
password
}
})
return res.status(200).json({message : '게시글을 삭제하였습니다.'});
} catch(err){
console.error(err);
return res.status(400).json({message : '데이터 형식이 올바르지 않습니다.'})
}
});
export default router;