92 lines
2.4 KiB
JavaScript
92 lines
2.4 KiB
JavaScript
const dealDB = require("../db/deal.db")
|
||
const commentDB = require("../db/comment.db")
|
||
const prisma = require("../db/client")
|
||
|
||
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 = Number(dealId)
|
||
|
||
const deal = await dealDB.findDeal({ id })
|
||
if (!deal) throw new Error("Deal bulunamadı.")
|
||
|
||
const include = { user: { select: { id:true,username: true, avatarUrl: true } } }
|
||
return commentDB.findComments({ dealId: id }, { include })
|
||
}
|
||
|
||
async function createComment({ dealId, userId, text, parentId = null }) {
|
||
if (!text || typeof text !== "string" || !text.trim()) {
|
||
throw new Error("Yorum boş olamaz.")
|
||
}
|
||
|
||
const trimmed = text.trim()
|
||
const include = { user: { select: { id: true, username: true, avatarUrl: true } } }
|
||
|
||
return prisma.$transaction(async (tx) => {
|
||
const deal = await dealDB.findDeal({ id: dealId }, {}, tx)
|
||
if (!deal) throw new Error("Deal bulunamadı.")
|
||
|
||
// ✅ Reply ise parent doğrula
|
||
let parent = null
|
||
if (parentId != null) {
|
||
const pid = Number(parentId)
|
||
if (!Number.isFinite(pid) || pid <= 0) throw new Error("Geçersiz parentId.")
|
||
|
||
parent = await commentDB.findComment({ id: pid }, { select: { id: true, dealId: true } }, tx)
|
||
if (!parent) throw new Error("Yanıtlanan yorum bulunamadı.")
|
||
if (parent.dealId !== dealId) throw new Error("Yanıtlanan yorum bu deal'a ait değil.")
|
||
}
|
||
|
||
const comment = await commentDB.createComment(
|
||
{
|
||
text: trimmed,
|
||
userId,
|
||
dealId,
|
||
parentId: parent ? parent.id : null,
|
||
},
|
||
{ include },
|
||
tx
|
||
)
|
||
|
||
await dealDB.updateDeal(
|
||
{ id: dealId },
|
||
{ commentCount: { increment: 1 } },
|
||
{},
|
||
tx
|
||
)
|
||
|
||
return comment
|
||
})
|
||
}
|
||
|
||
|
||
async function deleteComment(commentId, userId) {
|
||
|
||
const comments = await commentDB.findComments(
|
||
{ id: commentId },
|
||
{ select: { userId: true } }
|
||
)
|
||
|
||
if (!comments || comments.length === 0) throw new Error("Yorum bulunamadı.")
|
||
if (comments[0].userId !== userId) throw new Error("Bu yorumu silme yetkin yok.")
|
||
|
||
await commentDB.deleteComment({ id: commentId })
|
||
return { message: "Yorum silindi." }
|
||
}
|
||
|
||
async function commentChange(length,dealId){
|
||
|
||
|
||
|
||
}
|
||
|
||
module.exports = {
|
||
getCommentsByDealId,
|
||
createComment,
|
||
deleteComment,
|
||
}
|