model Posting {
id Int @id @default(autoincrement())
title String
content String
pharmacistId Int
pharmacist Pharmacist @relation(fields: [pharmacistId], references: [id])
Like Like[]
}
model Like {
postId Int
customerId Int
customer Customer @relation(fields: [customerId], references: [id])
posting Posting @relation(fields: [postId], references: [id])
@@id([postId, customerId])
}
공식문서를 참고해서 내파일의 schema.prisma 파일에도 추가하여 추가해주었다.
odel Posting {
id Int @id @default(autoincrement())
title String
content String
pharmacistId Int
pharmacist Pharmacist @relation(fields: [pharmacistId], references: [id])
postingLikes PostingLikes[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model PostingLikes {
postingId Int
customerId Int
customer Customer @relation(fields: [customerId], references: [id])
posting Posting @relation(fields: [postingId], references: [id])
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@id([postingId, customerId])
}
추가하고 나서 response 값이 잘 나오는것도 확인하였다.
@Put(':id/like') //FIXME: Body값을 customer로 수정
toggleLike(
@Param('id', ParseIntPipe) id: number,
@Body('customerId') customerId: number,
) {
return this.postingsService.toggleLike(id,customerId)
}
}
우선 아직 토큰이 생기지 않은 단게여서 유저를 구분할 수 있는 수단을
body값에 customerId 받기로 하였다.
그리고 params 값으로 게시물의 id 를 받도록 세팅하였다.
async toggleLike(id: number, customerId: number) {
const postingId = id;
let like = await this.prismaService.postingLikes.findUnique({
where: { postingId_customerId: { customerId, postingId } },
});
const message = like ? '좋아요 취소 완료' : '좋아요 완료';
const updatedLike = like
? await this.prismaService.postingLikes.delete({
where: { postingId_customerId: { customerId, postingId } },
})
: await this.prismaService.postingLikes.create({
data: { customerId, postingId },
});
return { result: updatedLike, message };
}
like는 우선 좋아요를 했는지 안했는지를 판단하기 위해서 만든 변수로써
db에서 파람스 값고 바디값에 해당하는 좋아요가 있는지 없는지를 먼저 찾는 부분이다.
그리고 updatedLike 는 like값이 true 라면 좋아요 취소를 하려는 부분이기 때문에 delete 를 해줘서 기존에 했던 좋아요 취소를 하고,
like값이 false 라면 아직 좋아요을 누르지 않은 즉 첫 좋아요를 누른 상태이기 때문에
좋아요를 만들도록 한 부분이다.