makearmy-app/app/api/account/route.ts
2025-09-30 17:04:37 -04:00

70 lines
2.7 KiB
TypeScript

// app/api/account/route.ts
export const runtime = "nodejs";
import { NextResponse } from "next/server";
import { requireBearer } from "@/app/api/_lib/auth";
const API = (process.env.NEXT_PUBLIC_API_BASE_URL || "").replace(/\/$/, "");
const bad = (m: string, c = 400) => NextResponse.json({ error: m }, { status: c });
/** GET: current user's profile */
export async function GET(req: Request) {
try {
const bearer = requireBearer(req); // ← pass req
const fields =
"id,username,first_name,last_name,email,location,avatar.id,avatar.filename_download";
const res = await fetch(
`${API}/users/me?fields=${encodeURIComponent(fields)}`,
{ headers: { Authorization: `Bearer ${bearer}` }, cache: "no-store" }
);
const j = await res.json().catch(() => ({}));
if (!res.ok) {
const msg = j?.errors?.[0]?.message || "Failed to load profile";
return NextResponse.json({ error: msg }, { status: res.status });
}
return NextResponse.json({ ok: true, user: j?.data ?? j });
} catch (e: any) {
const status = e?.status === 401 ? 401 : e?.status || 500;
return bad(e?.message || "Unexpected error", status);
}
}
/** PATCH: update editable fields for current user */
export async function PATCH(req: Request) {
try {
const bearer = requireBearer(req);
const body = await req.json().catch(() => ({}));
const payload: Record<string, any> = {};
if (typeof body.first_name === "string") payload.first_name = body.first_name.trim();
if (typeof body.last_name === "string") payload.last_name = body.last_name.trim();
if ("email" in body) {
const e = String(body.email ?? "").trim();
payload.email = e ? e : null; // optional; blank clears
}
if (typeof body.location === "string") payload.location = body.location.trim();
if (typeof body.avatar === "string") payload.avatar = body.avatar; // file id
if (!Object.keys(payload).length) return bad("No changes");
const res = await fetch(`${API}/users/me`, {
method: "PATCH",
headers: { Authorization: `Bearer ${bearer}`, "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
const j = await res.json().catch(() => ({}));
if (!res.ok) {
const msg = j?.errors?.[0]?.message || "Update failed";
return NextResponse.json({ error: msg }, { status: res.status });
}
return NextResponse.json({ ok: true });
} catch (e: any) {
const status = e?.status === 401 ? 401 : e?.status || 500;
return bad(e?.message || "Unexpected error", status);
}
}