cg / hackerproducts

64 files · 5,803 lines · 161.0 KB — Next.js 15, React 19, TypeScript, PostgreSQL, Object Storage, plain CSS.

Quick jump: page.tsx / page.tsx / globals.css / schema.sql / package.json

root / src / app / api / products / [slug] / upvote / route.ts

src/app/api/products/[slug]/upvote/route.ts · 55 lines · 1.4 KB← back to folder
1import { NextResponse } from "next/server";
2import { query } from "@/db";
3import { getCurrentUser } from "@/lib/auth";
4
5export async function POST(
6 _request: Request,
7 context: { params: Promise<{ slug: string }> }
8) {
9 const user = await getCurrentUser();
10 if (!user) {
11 return NextResponse.json({ error: "Sign in to upvote products." }, { status: 401 });
12 }
13
14 const { slug } = await context.params;
15 const prodRes = await query<{ id: string }>(
16 `SELECT id FROM products WHERE slug = $1 AND status = 'published' LIMIT 1`,
17 [slug]
18 );
19
20 const product = prodRes.rows[0];
21 if (!product) {
22 return NextResponse.json({ error: "Product not found." }, { status: 404 });
23 }
24
25 const existing = await query(
26 `SELECT 1 FROM upvotes WHERE user_id = $1 AND product_id = $2`,
27 [user.id, product.id]
28 );
29
30 let upvoted: boolean;
31 if (existing.rowCount && existing.rowCount > 0) {
32 await query(`DELETE FROM upvotes WHERE user_id = $1 AND product_id = $2`, [
33 user.id,
34 product.id,
35 ]);
36 upvoted = false;
37 } else {
38 await query(
39 `INSERT INTO upvotes (user_id, product_id) VALUES ($1, $2) ON CONFLICT DO NOTHING`,
40 [user.id, product.id]
41 );
42 upvoted = true;
43 }
44
45 const countRes = await query<{ count: string }>(
46 `SELECT COUNT(*)::int AS count FROM upvotes WHERE product_id = $1`,
47 [product.id]
48 );
49
50 return NextResponse.json({
51 upvoted,
52 count: Number(countRes.rows[0]?.count ?? 0),
53 });
54}
55
cg / hackerproducts — hacker products