2025-12-11 15:06:04 +01:00

98 lines
2.3 KiB
TypeScript

import { revalidateTag } from "next/cache";
import {
AUTH_COOKIE_NAME,
BE_BASE_URL,
USERS_CACHE_TAG,
} from "@/app/services/constants";
import { NextResponse } from "next/server";
import { cookies } from "next/headers";
// Interface matching the backend RegisterRequest and frontend IEditUserForm
interface RegisterRequest {
creator: string;
email: string;
first_name: string;
groups: string[];
job_title: string;
last_name: string;
merchants: string[];
phone: string;
username: string;
}
export async function POST(request: Request) {
try {
const body: RegisterRequest = await request.json();
// Get the auth token from cookies
const cookieStore = await cookies();
const token = cookieStore.get(AUTH_COOKIE_NAME)?.value;
if (!token) {
return NextResponse.json(
{
success: false,
message: "No authentication token found",
},
{ status: 401 }
);
}
// Call backend registration endpoint
const resp = await fetch(`${BE_BASE_URL}/api/v1/auth/register`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify(body),
});
// Handle backend response
if (!resp.ok) {
const errorData = await safeJson(resp);
console.error("Registration proxy error:", errorData);
return NextResponse.json(
{
success: false,
message: errorData?.message || "Registration failed",
error: errorData?.error || "Unknown error",
},
{ status: resp.status }
);
}
const data = await resp.json();
revalidateTag(USERS_CACHE_TAG);
return NextResponse.json(
{
success: true,
message: "Registration successful",
user: data.user || null,
},
{ status: 201 }
);
} catch (error) {
console.error("Registration proxy error:", error);
return NextResponse.json(
{
success: false,
message: "Internal server error during registration",
},
{ status: 500 }
);
}
}
// Helper function to safely parse JSON responses
async function safeJson(resp: Response) {
try {
return await resp.json();
} catch {
return null;
}
}