91 lines
2.4 KiB
TypeScript
91 lines
2.4 KiB
TypeScript
// app/api/users/[id]/route.ts
|
|
import { NextResponse } from "next/server";
|
|
|
|
const BE_BASE_URL = process.env.BE_BASE_URL || "http://localhost:5000";
|
|
const COOKIE_NAME = "auth_token";
|
|
|
|
export async function PATCH(
|
|
request: Request,
|
|
{ params }: { params: { id: string } }
|
|
) {
|
|
try {
|
|
console.log("[PATCH /users] - params", params);
|
|
const { id } = params;
|
|
const body = await request.json();
|
|
// Get the auth token from cookies
|
|
const { cookies } = await import("next/headers");
|
|
const cookieStore = cookies();
|
|
const token = (await cookieStore).get(COOKIE_NAME)?.value;
|
|
|
|
if (!token) {
|
|
return NextResponse.json(
|
|
{ message: "Missing Authorization header" },
|
|
{ status: 401 }
|
|
);
|
|
}
|
|
|
|
const response = await fetch(`${BE_BASE_URL}/users/${id}`, {
|
|
method: "PATCH",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
Authorization: `Bearer ${token}`,
|
|
},
|
|
body: JSON.stringify(body),
|
|
});
|
|
|
|
const data = await response.json();
|
|
return NextResponse.json(data, { status: response.status });
|
|
} catch (err: any) {
|
|
console.error("Proxy PATCH /users error:", err);
|
|
return NextResponse.json(
|
|
{ message: "Internal server error", error: err.message },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|
|
|
|
export async function DELETE(
|
|
_request: Request,
|
|
{ params }: { params: { id: string } }
|
|
) {
|
|
try {
|
|
const { id } = params;
|
|
const { cookies } = await import("next/headers");
|
|
const cookieStore = await cookies();
|
|
const token = cookieStore.get(COOKIE_NAME)?.value;
|
|
|
|
if (!token) {
|
|
return NextResponse.json(
|
|
{ message: "Missing Authorization header" },
|
|
{ status: 401 }
|
|
);
|
|
}
|
|
|
|
// According to swagger: /api/v1/users/{id}
|
|
const response = await fetch(`${BE_BASE_URL}/api/v1/users/${id}`, {
|
|
method: "DELETE",
|
|
headers: {
|
|
Authorization: `Bearer ${token}`,
|
|
},
|
|
});
|
|
|
|
// Some backends return empty body for DELETE; handle safely
|
|
let data: any = null;
|
|
try {
|
|
data = await response.json();
|
|
} catch {
|
|
data = { success: response.ok };
|
|
}
|
|
|
|
return NextResponse.json(data ?? { success: response.ok }, {
|
|
status: response.status,
|
|
});
|
|
} catch (err: any) {
|
|
console.error("Proxy DELETE /api/v1/users/{id} error:", err);
|
|
return NextResponse.json(
|
|
{ message: "Internal server error", error: err.message },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|