trptk/app/api/account/addresses/[id]/route.ts
2026-02-24 17:14:07 +01:00

75 lines
2.1 KiB
TypeScript

import { NextResponse } from "next/server";
import { getAuthToken, medusaAuthFetch } from "@/lib/auth";
import { parseBody, checkCsrf, pickAddressFields, isValidMedusaId } from "@/lib/apiUtils";
type Params = { params: Promise<{ id: string }> };
export async function POST(request: Request, { params }: Params) {
const csrfError = await checkCsrf();
if (csrfError) return csrfError;
const token = await getAuthToken();
if (!token) {
return NextResponse.json({ error: "Not authenticated" }, { status: 401 });
}
const { id } = await params;
if (!isValidMedusaId(id)) {
return NextResponse.json({ error: "Invalid address ID" }, { status: 400 });
}
const body = await parseBody(request);
if (!body) {
return NextResponse.json({ error: "Invalid request body" }, { status: 400 });
}
const address = pickAddressFields(body);
if (!address) {
return NextResponse.json({ error: "Invalid address data" }, { status: 400 });
}
try {
const data = await medusaAuthFetch<{ address: unknown }>(
`/store/customers/me/addresses/${id}`,
{
method: "POST",
body: JSON.stringify(address),
},
);
return NextResponse.json(data);
} catch (e) {
console.error("[account:addresses:update]", (e as Error).message);
return NextResponse.json(
{ error: "Failed to update address" },
{ status: 500 },
);
}
}
export async function DELETE(_request: Request, { params }: Params) {
const csrfError = await checkCsrf();
if (csrfError) return csrfError;
const token = await getAuthToken();
if (!token) {
return NextResponse.json({ error: "Not authenticated" }, { status: 401 });
}
const { id } = await params;
if (!isValidMedusaId(id)) {
return NextResponse.json({ error: "Invalid address ID" }, { status: 400 });
}
try {
await medusaAuthFetch(`/store/customers/me/addresses/${id}`, {
method: "DELETE",
});
return NextResponse.json({ success: true });
} catch (e) {
console.error("[account:addresses:delete]", (e as Error).message);
return NextResponse.json(
{ error: "Failed to delete address" },
{ status: 500 },
);
}
}