Initial role user app
This commit is contained in:
@@ -0,0 +1,94 @@
|
||||
import "server-only";
|
||||
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
import { clearSessionToken, getSessionToken } from "@/lib/session";
|
||||
import type { ApiEnvelope } from "@/lib/types";
|
||||
|
||||
export class BackendError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public status: number
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
export function getBackendBaseUrl() {
|
||||
return process.env.ACCESS_MANAGE_API_BASE_URL || "http://localhost:3500/api";
|
||||
}
|
||||
|
||||
function toUrl(path: string) {
|
||||
return new URL(path.replace(/^\//, ""), `${getBackendBaseUrl().replace(/\/$/, "")}/`);
|
||||
}
|
||||
|
||||
async function parseBackendResponse<T>(response: Response): Promise<T> {
|
||||
const contentType = response.headers.get("content-type") || "";
|
||||
const payload = contentType.includes("application/json") ? await response.json() : null;
|
||||
|
||||
if (!response.ok || payload?.success === false) {
|
||||
throw new BackendError(payload?.message || response.statusText || "请求失败", response.status);
|
||||
}
|
||||
|
||||
if (payload && typeof payload === "object" && "data" in payload) {
|
||||
return payload.data as T;
|
||||
}
|
||||
|
||||
return payload as T;
|
||||
}
|
||||
|
||||
export async function backendRequest<T>(
|
||||
path: string,
|
||||
init: RequestInit & { token?: string; allowUnauthorized?: boolean } = {}
|
||||
) {
|
||||
const token = init.token ?? (await getSessionToken());
|
||||
const headers = new Headers(init.headers);
|
||||
|
||||
headers.set("Accept", "application/json");
|
||||
if (init.body && !headers.has("Content-Type")) {
|
||||
headers.set("Content-Type", "application/json");
|
||||
}
|
||||
if (token) {
|
||||
headers.set("Authorization", `Bearer ${token}`);
|
||||
}
|
||||
|
||||
const response = await fetch(toUrl(path), {
|
||||
...init,
|
||||
headers,
|
||||
cache: "no-store"
|
||||
});
|
||||
|
||||
return parseBackendResponse<T>(response);
|
||||
}
|
||||
|
||||
export async function requireBackendData<T>(path: string) {
|
||||
try {
|
||||
return await backendRequest<T>(path);
|
||||
} catch (error) {
|
||||
if (error instanceof BackendError && error.status === 401) {
|
||||
redirect("/api/auth/logout?next=/login");
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function proxyBackendJson<T>(path: string, init: RequestInit = {}) {
|
||||
try {
|
||||
const data = await backendRequest<T>(path, init);
|
||||
return Response.json({ success: true, data } satisfies ApiEnvelope<T>);
|
||||
} catch (error) {
|
||||
return backendErrorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function backendErrorResponse(error: unknown, fallbackMessage = "请求失败") {
|
||||
const status = error instanceof BackendError ? error.status : 500;
|
||||
const message = error instanceof Error ? error.message : fallbackMessage;
|
||||
|
||||
if (status === 401) {
|
||||
await clearSessionToken();
|
||||
}
|
||||
|
||||
return Response.json({ success: false, data: null, message }, { status });
|
||||
}
|
||||
Reference in New Issue
Block a user