Download api/characters/route.ts from Jakecybr/dnd2: direct link, hf CLI and curl.
- Browser
- Download file 2.07 kB
-
https://huggingface.co/spaces/Jakecybr/dnd2/resolve/main/api/characters/route.ts
- Command line
-
hf download hf://spaces/Jakecybr/dnd2/api/characters/route.ts
-
curl -L -o route.ts https://huggingface.co/spaces/Jakecybr/dnd2/resolve/main/api/characters/route.ts
2.07 kB
| import { NextResponse } from "next/server"; | |
| import { cookies } from "next/headers"; | |
| import db from "@/lib/db"; | |
| function getUserId(): number | null { | |
| const token = cookies().get("session")?.value; | |
| if (!token) return null; | |
| const row = db.prepare("SELECT user_id, expires_at FROM sessions WHERE token = ?").get(token) as any; | |
| if (!row) return null; | |
| if (new Date(row.expires_at).getTime() < Date.now()) return null; | |
| return row.user_id as number; | |
| } | |
| function isDM(userId: number): boolean { | |
| const u = db.prepare("SELECT role FROM users WHERE id = ?").get(userId) as any; | |
| return u?.role === "dm"; | |
| } | |
| export async function GET(req: Request) { | |
| const userId = getUserId(); | |
| if (!userId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); | |
| const url = new URL(req.url); | |
| const all = url.searchParams.get("all") === "1"; | |
| const rows = all && isDM(userId) | |
| ? db.prepare("SELECT * FROM characters WHERE is_deleted = 0 ORDER BY updated_at DESC").all() | |
| : db.prepare("SELECT * FROM characters WHERE user_id = ? AND is_deleted = 0 ORDER BY updated_at DESC").all(userId); | |
| return NextResponse.json({ success: true, characters: rows }); | |
| } | |
| export async function POST(req: Request) { | |
| const userId = getUserId(); | |
| if (!userId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); | |
| const body = await req.json(); | |
| const name = (body.name || "").trim(); | |
| if (!name) return NextResponse.json({ error: "Name required" }, { status: 400 }); | |
| const class_type = (body.class_type || "").trim(); | |
| const inventory = JSON.stringify(body.inventory ?? []); | |
| const stats = JSON.stringify(body.stats ?? {}); | |
| const appearance = JSON.stringify(body.appearance ?? {}); | |
| const id = db | |
| .prepare( | |
| "INSERT INTO characters (user_id, name, class_type, inventory, stats, appearance) VALUES (?, ?, ?, ?, ?, ?)" | |
| ) | |
| .run(userId, name, class_type, inventory, stats, appearance).lastInsertRowid; | |
| return NextResponse.json({ success: true, characterId: id }); | |
| } | |