HotTRDealsBackend/services/deal/dealService.js

107 lines
2.4 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.

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 } }, // JWTden 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 }