게시글 삭제에 이어서 게시글 수정할 때의 코드를 다시 손을 봐야했다. 게시글 수정을 통해 장소를 변경하는 경우도 발생하는데 그럴 때 location 정보도 같이 수정이 됐다.
location에 한 장소 당 한 개 씩만 있어야하는 location테이블에 여러 장소가 존재하게 되어버렸고, 같은 장소여도 다른 locationId를 가지게 되었다. 그럼 추후에 locationId를 이용해서 활용하는 기능에서 이상이 생길듯 했다.
그래서 기존 코드인 아래 코드를
// 게시물 수정
router.patch("/posts/:postId", authMiddleware, async (req, res, next) => {
try {
const { userId } = req.user;
const { postId } = req.params;
const validation = await editPostsSchema.validateAsync(req.body)
const { address, content, star, storeName, placeInfoId } = validation;
// 확인사항: 주소를 바꾸는 경우에는 latitude, longitude, placeInfoId도 받아서 같이 수정해야함
const post = await prisma.posts.findFirst({
where: { postId: +postId },
});
if (!post) {
res.status(404).json({ message: "존재하지 않는 게시글 입니다." });
}
if (post.UserId !== userId) {
return res
.status(403)
.json({ message: "삭제할 권한이 존재하지 않습니다." });
}
await prisma.$transaction(async (prisma) => {
const createPost = await prisma.posts.update({
where: { postId: +postId, UserId: +userId },
data: {
content,
star,
},
});
const starAvg = await prisma.posts.aggregate({
where: { LocationId: createPost.LocationId },
_avg: {
star: true,
},
});
await prisma.locations.update({
where: {
locationId: createPost.LocationId,
},
data: {
starAvg: starAvg._avg.star,
address,
storeName,
placeInfoId
},
});
});
return res.status(201).json({ message: "게시물을 수정하였습니다." });
} catch (error) {
next(error);
}
});
아래 코드처럼 수정을 했다.