Update app/api/character/route.ts
Browse files21 unmodified lines2223242526272829303132333435363738394041424344452 unmodified lines48495051525354555657585921 unmodified linesreturn NextResponse.json({ character, journals });} catch (err) {console.error("GET Character Error:", err);return NextResponse.json({ character: null, journals: [] });}}export async function POST(req: Request) {const body = await req.json();const { userId, type } = body;// SECURITY CHECK: Does this user actually exist?const userExists = db.prepare('SELECT id FROM users WHERE id = ?').get(userId);if (!userExists) {return NextResponse.json({ error: "User ID not found. Please logout and login again." }, { status: 400 });}try {if (type === 'UPDATE_CHAR') {const exists = db.prepare('SELECT id FROM characters WHERE user_id = ?').get(userId);if (exists) {db.prepare('UPDATE characters SET name=?, class_type=?, inventory=? WHERE user_id=?').run(body.name, body.class_type, body.inventory, userId);} else {2 unmodified lines}}if (type === 'ADD_JOURNAL') {db.prepare('INSERT INTO journal (user_id, title, content, is_public) VALUES (?, ?, ?, ?)').run(userId, body.title, body.content, body.is_public ? 1 : 0);}return NextResponse.json({ success: true });} catch (error) {console.error("Database Write Error:", error);return NextResponse.json({ error: "Save failed" }, { status: 500 });21 unmodified lines2223242526272829303132333435363738394041424344454647484950512 unmodified lines545556575859606162636465666721 unmodified linesreturn NextResponse.json({ character, journals });} catch (err) {console.error("GET Character Error:", err);// Return empty data instead of crashingreturn NextResponse.json({ character: null, journals: [] });}}export async function POST(req: Request) {try {const body = await req.json();const { userId, type } = body;// 1. SECURITY CHECK: Does this user actually exist?// This prevents the "Foreign Key Constraint" crashconst userCheck = db.prepare('SELECT id FROM users WHERE id = ?').get(userId);if (!userCheck) {console.warn(`Blocked attempt to save for non-existent User ID: ${userId}`);return NextResponse.json({ error: "User not found. Please logout." }, { status: 401 });}// 2. Handle Character Updatesif (type === 'UPDATE_CHAR') {const charExists = db.prepare('SELECT id FROM characters WHERE user_id = ?').get(userId);if (charExists) {db.prepare('UPDATE characters SET name=?, class_type=?, inventory=? WHERE user_id=?').run(body.name, body.class_type, body.inventory, userId);} else {2 unmodified lines}}// 3. Handle Journal Entriesif (type === 'ADD_JOURNAL') {db.prepare('INSERT INTO journal (user_id, title, content, is_public) VALUES (?, ?, ?, ?)').run(userId, body.title, body.content, body.is_public ? 1 : 0);}return NextResponse.json({ success: true });} catch (error) {console.error("Database Write Error:", error);return NextResponse.json({ error: "Save failed" }, { status: 500 });
app/api/character/route.ts+18-10