feat: 接通后台渲染异常上报与响应契约校验
This commit is contained in:
1 parent
330d67adc1
commit
adcaa12970
22 files changed
+845
-33
No files matched your search
@@ -1,3 +1,4 @@
|
||||
import type { ZodType } from "zod";
|
||||
import type { ApiErrorBody } from "../types/common.js";
|
||||
|
||||
export interface FetchResponse {
|
||||
@@ -17,15 +18,20 @@ export interface ApiClientOptions {
|
||||
token?: string;
|
||||
}
|
||||
|
||||
export type RequestFn = <T>(
|
||||
path: string,
|
||||
options?: { method?: string; body?: unknown; rawBody?: unknown },
|
||||
) => Promise<T>;
|
||||
export interface RequestOptions {
|
||||
method?: string;
|
||||
body?: unknown;
|
||||
rawBody?: unknown;
|
||||
/** 响应体的运行时契约;不匹配时抛出 ApiClientContractError,而不是把脏数据交给页面。 */
|
||||
expect?: ZodType<unknown>;
|
||||
}
|
||||
|
||||
export type RequestFn = <T>(path: string, options?: RequestOptions) => Promise<T>;
|
||||
|
||||
export async function request<T>(
|
||||
state: { baseUrl: string; fetcher: FetchLike; token?: string | undefined },
|
||||
path: string,
|
||||
options: { method?: string; body?: unknown; rawBody?: unknown } = {},
|
||||
options: RequestOptions = {},
|
||||
): Promise<T> {
|
||||
const headers: Record<string, string> = { accept: "application/json" };
|
||||
if (options.rawBody === undefined && options.body !== undefined)
|
||||
@@ -48,9 +54,37 @@ export async function request<T>(
|
||||
)(`${state.baseUrl}${path}`, init);
|
||||
const body = await response.json();
|
||||
if (!response.ok) throw new ApiClientError(response.status, body as ApiErrorBody);
|
||||
if (options.expect) assertResponseContract(options.expect, body, path);
|
||||
return body as T;
|
||||
}
|
||||
|
||||
/** 接口返回结构不符合客户端契约:携带请求路径与首个校验问题,方便定位。 */
|
||||
export class ApiClientContractError extends Error {
|
||||
constructor(
|
||||
readonly path: string,
|
||||
readonly issues: string[],
|
||||
) {
|
||||
super(`接口返回数据结构不符合契约:${path}${issues.length > 0 ? `(${issues[0]})` : ""}`);
|
||||
this.name = "ApiClientContractError";
|
||||
}
|
||||
}
|
||||
|
||||
export function assertResponseContract(
|
||||
schema: ZodType<unknown>,
|
||||
value: unknown,
|
||||
path: string,
|
||||
): void {
|
||||
const result = schema.safeParse(value);
|
||||
if (result.success) return;
|
||||
throw new ApiClientContractError(
|
||||
path,
|
||||
result.error.issues.map((issue) => {
|
||||
const location = issue.path.length > 0 ? issue.path.join(".") + ":" : "";
|
||||
return location + issue.message;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export class ApiClientError extends Error {
|
||||
constructor(
|
||||
readonly status: number,
|
||||
|
||||
Reference in new issue
Block a user