HotTRDealsBackend/services/deal/commentService.js

67 lines
2.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// services/deal/commentService.js
const { PrismaClient } = require("@prisma/client")
const prisma = new PrismaClient()
function assertPositiveInt(v, name = "id") {
const n = Number(v)
if (!Number.isInteger(n) || n <= 0) throw new Error(`Geçersiz ${name}.`)
return n
}
async function getCommentsByDealId(dealId) {
const id = assertPositiveInt(dealId, "dealId")
// Deal mevcut mu kontrol et
const deal = await prisma.deal.findUnique({ where: { id } })
if (!deal) throw new Error("Deal bulunamadı.")
return prisma.comment.findMany({
where: { dealId: id },
include: { user: { select: { username: true } } },
orderBy: { createdAt: "desc" },
})
}
async function createComment({ dealId, userId, text }) {
// Basit doğrulamalar
const dId = assertPositiveInt(dealId, "dealId")
const uId = assertPositiveInt(userId, "userId")
if (!text || typeof text !== "string" || !text.trim())
throw new Error("Yorum boş olamaz.")
// Deal var mı kontrol et
const deal = await prisma.deal.findUnique({ where: { id: dId } })
if (!deal) throw new Error("Deal bulunamadı.")
// (Opsiyonel) Kullanıcı var mı kontrolü (ek güvenlik)
const user = await prisma.user.findUnique({ where: { id: uId } })
if (!user) throw new Error("Kullanıcı bulunamadı.")
const comment = await prisma.comment.create({
data: {
text: text.trim(),
userId: uId,
dealId: dId,
},
include: {
user: { select: { username: true } },
},
})
return comment
}
async function deleteComment(commentId, userId) {
const cId = assertPositiveInt(commentId, "commentId")
const uId = assertPositiveInt(userId, "userId")
const comment = await prisma.comment.findUnique({ where: { id: cId } })
if (!comment) throw new Error("Yorum bulunamadı.")
if (comment.userId !== uId) throw new Error("Bu yorumu silme yetkin yok.")
await prisma.comment.delete({ where: { id: cId } })
return { message: "Yorum silindi." }
}
module.exports = { getCommentsByDealId, createComment, deleteComment }