b7433acba4
新增角色探索、收藏、世界书和身份资料;接入流式打字、停止重生成、固定记忆、会话分支与导出;适配手机和桌面并保持实验只由后台控制。
119 lines
3.2 KiB
TypeScript
119 lines
3.2 KiB
TypeScript
/** 服务端后端访问与会话错误转换,统一保留业务错误文案。 */
|
|
import "server-only";
|
|
|
|
import { redirect } from "next/navigation";
|
|
|
|
import { clearSessionToken, getSessionToken } from "@/lib/session";
|
|
import type { ApiEnvelope } from "@/lib/types";
|
|
|
|
/** 保留后端状态以便 BFF 清理失效会话。 */
|
|
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?.error?.message ||
|
|
payload?.message ||
|
|
response.statusText ||
|
|
"请求失败",
|
|
response.status,
|
|
);
|
|
}
|
|
|
|
if (payload && typeof payload === "object" && "data" in payload) {
|
|
return payload.data as T;
|
|
}
|
|
|
|
return payload as T;
|
|
}
|
|
|
|
/** 为服务端请求附加 HttpOnly 会话并禁止缓存私有数据。 */
|
|
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);
|
|
}
|
|
|
|
/** 页面数据要求登录,失效时通过登出路由清理 Cookie。 */
|
|
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;
|
|
}
|
|
}
|
|
|
|
/** 包装普通 JSON 业务接口,流式对话使用专用 BFF。 */
|
|
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);
|
|
}
|
|
}
|
|
|
|
/** 对浏览器返回统一错误,401 时同步清理 Cookie。 */
|
|
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 });
|
|
}
|