107 lines
2.4 KiB
JavaScript
107 lines
2.4 KiB
JavaScript
const { PrismaClient } = require("@prisma/client")
|
||
const prisma = new PrismaClient()
|
||
|
||
|
||
async function getAllDeals(page = 1, limit = 10) {
|
||
const skip = (page - 1) * limit
|
||
|
||
const [deals, total] = await Promise.all([
|
||
prisma.deal.findMany({
|
||
skip,
|
||
take: limit,
|
||
orderBy: { createdAt: "desc" },
|
||
include: {
|
||
user: { select: { username: true } },
|
||
images: {
|
||
orderBy: { order: "asc" },
|
||
take: 1, // sadece kapak fotoğrafı
|
||
select: { imageUrl: true },
|
||
},
|
||
},
|
||
}),
|
||
prisma.deal.count(),
|
||
])
|
||
|
||
return {
|
||
page,
|
||
total,
|
||
totalPages: Math.ceil(total / limit),
|
||
results: deals,
|
||
}
|
||
}
|
||
|
||
async function getDealById(id) {
|
||
return prisma.deal.findUnique({
|
||
where: { id: Number(id) },
|
||
include: {
|
||
user: { select: { username: true } },
|
||
images: {
|
||
orderBy: { order: "asc" }, // tüm fotoğrafları sırayla getir
|
||
select: { id: true, imageUrl: true, order: true },
|
||
},
|
||
},
|
||
})
|
||
}
|
||
|
||
|
||
|
||
async function createDeal(data, userId) {
|
||
return prisma.deal.create({
|
||
data: {
|
||
title: data.title,
|
||
description: data.description,
|
||
url: data.url,
|
||
imageUrl: data.imageUrl,
|
||
price: data.price,
|
||
user: { connect: { id: userId } }, // JWT’den gelen userId burada bağlanır
|
||
},
|
||
})
|
||
}
|
||
|
||
async function voteDeal(dealId, userId, voteType) {
|
||
if (!dealId || !userId || !voteType) throw new Error("Eksik veri")
|
||
|
||
const existingVote = await prisma.dealVote.findFirst({
|
||
where: { dealId, userId },
|
||
})
|
||
|
||
if (existingVote) {
|
||
await prisma.dealVote.update({
|
||
where: { id: existingVote.id },
|
||
data: { voteType },
|
||
})
|
||
} else {
|
||
await prisma.dealVote.create({
|
||
data: { dealId, userId, voteType },
|
||
})
|
||
}
|
||
|
||
const upvotes = await prisma.dealVote.count({
|
||
where: { dealId, voteType: "UP" },
|
||
})
|
||
const downvotes = await prisma.dealVote.count({
|
||
where: { dealId, voteType: "DOWN" },
|
||
})
|
||
|
||
const score = upvotes - downvotes
|
||
|
||
await prisma.deal.update({
|
||
where: { id: dealId },
|
||
data: { score },
|
||
})
|
||
|
||
return score
|
||
}
|
||
|
||
async function getVotes(dealId) {
|
||
const upvotes = await prisma.dealVote.count({
|
||
where: { dealId: Number(dealId), voteType: "UP" },
|
||
})
|
||
const downvotes = await prisma.dealVote.count({
|
||
where: { dealId: Number(dealId), voteType: "DOWN" },
|
||
})
|
||
return { upvotes, downvotes, score: upvotes - downvotes }
|
||
}
|
||
|
||
module.exports = { getAllDeals, getDealById, createDeal, voteDeal, getVotes }
|