cg / hackerproducts

63 files · 5,740 lines · 159.1 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 / profile / route.ts

src/app/api/profile/route.ts · 72 lines · 2.1 KB← back to folder
1import { NextResponse } from "next/server";
2import { query } from "@/db";
3import { getCurrentUser } from "@/lib/auth";
4import {
5 isReservedUsername,
6 sanitizeUsername,
7 validateHttpUrl,
8 validateOptionalImageUrl,
9} from "@/lib/validation";
10
11export async function PATCH(request: Request) {
12 const user = await getCurrentUser();
13 if (!user) {
14 return NextResponse.json({ error: "Sign in required." }, { status: 401 });
15 }
16
17 const body = (await request.json().catch(() => null)) as {
18 username?: string;
19 bio?: string;
20 website_url?: string;
21 avatar_url?: string | null;
22 } | null;
23
24 if (!body) {
25 return NextResponse.json({ error: "Invalid request body." }, { status: 400 });
26 }
27
28 const username = sanitizeUsername(body.username ?? user.username);
29 if (!username || username.length < 2 || isReservedUsername(username)) {
30 return NextResponse.json(
31 { error: "Username must be at least 2 characters (letters, numbers, -, _) and not reserved." },
32 { status: 400 }
33 );
34 }
35
36 if (username !== user.username) {
37 const taken = await query(`SELECT 1 FROM users WHERE LOWER(username) = LOWER($1) AND id <> $2`, [
38 username,
39 user.id,
40 ]);
41 if (taken.rowCount && taken.rowCount > 0) {
42 return NextResponse.json({ error: "That username is already taken." }, { status: 409 });
43 }
44 }
45
46 const bio = (body.bio ?? "").trim().slice(0, 300);
47 let websiteUrl = "";
48 if (body.website_url && body.website_url.trim()) {
49 const valid = validateHttpUrl(body.website_url);
50 if (!valid) {
51 return NextResponse.json({ error: "Please enter a valid website URL." }, { status: 400 });
52 }
53 websiteUrl = valid;
54 }
55
56 const avatarUrl =
57 body.avatar_url === undefined
58 ? user.avatar_url
59 : body.avatar_url?.trim()
60 ? validateOptionalImageUrl(body.avatar_url)
61 : null;
62
63 await query(
64 `UPDATE users
65 SET username = $1, bio = $2, website_url = $3, avatar_url = $4, updated_at = NOW()
66 WHERE id = $5`,
67 [username, bio, websiteUrl, avatarUrl, user.id]
68 );
69
70 return NextResponse.json({ ok: true, username });
71}
72
cg / hackerproducts — hacker products