HotTRDealsBackend/routes/dealVoteRoutes.js
2025-10-30 22:49:11 +00:00

73 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.

const express = require("express");
const { PrismaClient } = require("@prisma/client");
const authMiddleware = require("../middleware/authMiddleware");
const router = express.Router();
const prisma = new PrismaClient();
// Oy verme
router.post("/", authMiddleware, async (req, res) => {
console.log("body:", req.body);
console.log("user:", req.user);
try {
const { dealId, voteType } = req.body;
const userId = req.user.userId;
if (!dealId || !userId || !voteType)
return res.status(400).json({ error: "Eksik veri." });
const existingVote = await prisma.dealVote.findFirst({
where: { dealId, userId },
});
let vote;
if (existingVote) {
// Aynı kullanıcı aynı ilana yeniden oy verirse güncelle
vote = await prisma.dealVote.update({
where: { id: existingVote.id },
data: { voteType },
});
} else {
vote = await prisma.dealVote.create({
data: { dealId, userId, voteType },
});
}
// Toplam oy sayısını güncelle
const upvotes = await prisma.dealVote.count({
where: { dealId, voteType: "UP" },
});
const downvotes = await prisma.dealVote.count({
where: { dealId, voteType: "DOWN" },
});
await prisma.deal.update({
where: { id: dealId },
data: { score: upvotes - downvotes },
});
res.json({ vote, score: upvotes - downvotes });
} catch (err) {
console.error(err);
res.status(500).json({ error: "Sunucu hatası." });
}
});
// Belirli bir deal için oyları çek
router.get("/:dealId", async (req, res) => {
try {
const { dealId } = req.params;
const upvotes = await prisma.dealVote.count({
where: { dealId: parseInt(dealId), voteType: "UP" },
});
const downvotes = await prisma.dealVote.count({
where: { dealId: parseInt(dealId), voteType: "DOWN" },
});
res.json({ upvotes, downvotes, score: upvotes - downvotes });
} catch (err) {
console.error(err);
res.status(500).json({ error: "Sunucu hatası." });
}
});
module.exports = router;