53 lines
1.9 KiB
TypeScript
53 lines
1.9 KiB
TypeScript
import { NextResponse } from "next/server";
|
|
import { updateCart } from "@/lib/medusa";
|
|
import { getAuthToken } from "@/lib/auth";
|
|
import { parseBody, isNonEmptyString, isValidEmail, isValidMedusaId, badRequest, checkCsrf, pickAddressFields } from "@/lib/apiUtils";
|
|
|
|
// POST /api/checkout/update — update cart with email + addresses
|
|
export async function POST(request: Request) {
|
|
const csrfError = await checkCsrf();
|
|
if (csrfError) return csrfError;
|
|
|
|
const body = await parseBody<{
|
|
cartId?: unknown;
|
|
email?: unknown;
|
|
shipping_address?: unknown;
|
|
billing_address?: unknown;
|
|
}>(request);
|
|
if (!body) return badRequest("Invalid request body");
|
|
|
|
const { cartId, email, shipping_address, billing_address } = body;
|
|
|
|
if (!isNonEmptyString(cartId)) {
|
|
return badRequest("Missing cartId");
|
|
}
|
|
if (!isValidMedusaId(cartId)) {
|
|
return badRequest("Invalid cart ID format");
|
|
}
|
|
if (email !== undefined && !isValidEmail(email)) {
|
|
return badRequest("Invalid email address");
|
|
}
|
|
|
|
// Sanitize address fields to prevent mass assignment
|
|
const sanitizedShipping = shipping_address ? pickAddressFields(shipping_address) : undefined;
|
|
const sanitizedBilling = billing_address ? pickAddressFields(billing_address) : undefined;
|
|
|
|
// Pass auth token so Medusa associates the cart with the logged-in customer
|
|
const authToken = (await getAuthToken()) ?? undefined;
|
|
|
|
try {
|
|
const cart = await updateCart(
|
|
cartId,
|
|
{
|
|
email: typeof email === "string" ? email.trim().toLowerCase() : undefined,
|
|
shipping_address: sanitizedShipping as Parameters<typeof updateCart>[1]["shipping_address"],
|
|
billing_address: sanitizedBilling as Parameters<typeof updateCart>[1]["billing_address"],
|
|
},
|
|
authToken,
|
|
);
|
|
return NextResponse.json(cart);
|
|
} catch (e) {
|
|
console.error("[checkout:update]", (e as Error).message);
|
|
return NextResponse.json({ error: "Failed to update cart" }, { status: 500 });
|
|
}
|
|
}
|