import express from "express";
import { PrismaClient } from "@prisma/client";
const router = express.Router(); // express.Router()를 이용해 라우터를 생성합니다.
const prisma = new PrismaClient({
// Prisma를 이용해 데이터베이스를 접근할 때, SQL을 출력해줍니다.
log: ["query", "info", "warn", "error"],
// 에러 메시지를 평문이 아닌, 개발자가 읽기 쉬운 형태로 출력해줍니다.
errorFormat: "pretty",
}); // PrismaClient 인스턴스를 생성합니다.
router.post("/posts", async (req, res, next) => {
const { title, content, password } = req.body;
const post = await prisma.posts.create({
data: {
title: title,
content: content,
password: password,
},
});
return res.status(201).json({ data: post });
});
//게시글 목록 조회 API
router.get("/posts", async (req, res, next) => {
//테이블 posts의 모든 데이터 목록 조회(findMany)
//findMany는 select 문법에서 노출시키고 싶은 것만 true로 표시하고, 그렇지 않은 건 아예 기입하면 안댐, postId: false << 이렇게 하면 에러남
//select문 안쓰면 목록에 들어있는 모든 데이터가 다 조회됨
const posts = await prisma.posts.findMany({
//프리즈마 문법(select)), 데이터 목록에서 노출시키고 싶은 것과 그렇지 않은 것을 선택하게 해줌
select: {
postId: true,
title: true,
createdAt: true,
updatedAt: true,
},
});
//성공적인 조회 상태 번호는 200
return res.status(200).json({ data: posts });
});
//게시글 상세 조회 API
router.get("/posts/:postId", async (req, res, next) => {
const { postId } = req.params;
const post = await prisma.posts.findFirst({
//select from where 문(sql)
//postId는 schema.prisma에 숫자형으로 정의되어 있지만, params 데이터는 기본적으로 문자형이다. 그래서 where 절이 에러 남
//그래서 숫자로 바꿔줘야 함
where: {
postId: +postId,
},
select: {
postId: true,
title: true,
content: true,
createdAt: true,
updatedAt: true,
},
});
return res.status(200).json({ data: post });
});
//게시글 수정 API
router.put("/posts/:postId", async (req, res, next) => {
const { postId } = req.params;
const { title, content, password } = req.body;
//findUnique는 특정 테이블의 콜럼 중 유니크나 기본 키 제약 조건이 걸린 콜럼에만 사용 가능
const post = await prisma.posts.findUnique({
where: {
postId: +postId,
// password: password, << 이렇게 하면 안댐
},
});
if (!post) {
return res
.status(404)
.json({ message: "해당 게시글이 존재하지 않습니다." });
} else if (post.password !== password) {
//401 = 인증실패 상태 번호
return res.status(401).json({ message: "비밀번호가 일치하지 않습니다." });
}
await prisma.posts.update({
//여기 data는 아무래도 명령어인듯?
data: {
title: title,
content: content,
},
where: {
postId: +postId,
password: password,
},
});
return res.status(200).json({ data: "게시글이 수정되었습니다." });
});
//게시글 삭제 API
router.delete("/posts/:postId", async (req, res, next) => {
const { postId } = req.params;
const { password } = req.body;
const post = await prisma.posts.findUnique({
where: {
postId: +postId,
},
});
if (!post)
return res
.status(404)
.json({ message: "해당 게시글이 존재하지 않습니다." });
else if (password !== post.password)
return res.status(400).json({ message: "비밀번호가 일치하지 않습니다." });
await prisma.posts.delete({
where: {
postId: +postId,
},
});
return res.status(200).json({ data: "게시글이 삭제되었습니다." });
});
export default router;
Prisma 리팩토링
posts.router.js에 있었던 Prisma 생성자 함수를 별도의 모듈로 모듈화 함