Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 | 8x 8x 8x 8x 8x 48x 20x 20x 20x 49x 49x 49x 49x 49x 49x 17x 49x 49x 49x 49x 48x 48x 48x 1x 47x 47x 2x 1x 1x 1x 49x | export type BusinessId = string;
export interface ApiEnvelope<T> {
code: string;
message: string;
data: T;
timestamp: string;
}
export interface PageResponse<T> {
items: T[];
page: number;
size: number;
total: number;
}
export interface CursorPageResponse<T> {
items: T[];
nextCursor: string | null;
hasMore: boolean;
}
export type ApiErrorKind =
| "network"
| "timeout"
| "http"
| "business"
| "invalid-response";
export class ApiError extends Error {
readonly kind: ApiErrorKind;
readonly code: string;
readonly status: number | undefined;
constructor(
kind: ApiErrorKind,
code: string,
message: string,
status?: number,
options?: ErrorOptions,
) {
super(message, options);
this.name = "ApiError";
this.kind = kind;
this.code = code;
this.status = status;
}
}
export interface ApiClientOptions {
baseUrl?: string;
timeoutMs?: number;
tokenProvider?: () => string | null;
}
export interface ApiRequestOptions extends RequestInit {
timeoutMs?: number;
}
export interface ApiClient {
request<T>(path: string, options?: ApiRequestOptions): Promise<T>;
}
function isEnvelope(value: unknown): value is ApiEnvelope<unknown> {
return Boolean(
value
&& typeof value === "object"
&& "code" in value
&& "message" in value
&& "timestamp" in value,
);
}
export function createApiClient(options: ApiClientOptions = {}): ApiClient {
const baseUrl = options.baseUrl?.replace(/\/$/, "") ?? "";
const defaultTimeoutMs = options.timeoutMs ?? 8000;
return {
async request<T>(path: string, requestOptions: ApiRequestOptions = {}): Promise<T> {
const controller = new AbortController();
const timeoutMs = requestOptions.timeoutMs ?? defaultTimeoutMs;
const timeout = globalThis.setTimeout(() => controller.abort(), timeoutMs);
const headers = new Headers(requestOptions.headers);
headers.set("Accept", "application/json");
if (requestOptions.body && !headers.has("Content-Type")) {
headers.set("Content-Type", "application/json");
}
const token = options.tokenProvider?.();
Iif (token) {
headers.set("Authorization", `Bearer ${token}`);
}
try {
const response = await fetch(`${baseUrl}${path}`, {
...requestOptions,
headers,
signal: controller.signal,
});
const payload: unknown = await response.json().catch((cause: unknown) => {
throw new ApiError(
"invalid-response",
"INVALID_RESPONSE",
"服务返回了无法识别的响应。",
response.status,
{ cause },
);
});
Iif (!isEnvelope(payload)) {
throw new ApiError(
"invalid-response",
"INVALID_RESPONSE",
"服务响应缺少统一结果结构。",
response.status,
);
}
if (!response.ok) {
throw new ApiError(
"http",
payload.code || `HTTP_${response.status}`,
payload.message || "请求未完成。",
response.status,
);
}
Iif (payload.code !== "OK") {
throw new ApiError(
"business",
payload.code,
payload.message || "业务状态不允许执行当前操作。",
response.status,
);
}
return payload.data as T;
} catch (error) {
if (error instanceof ApiError) {
throw error;
}
Iif (error instanceof DOMException && error.name === "AbortError") {
throw new ApiError(
"timeout",
"REQUEST_TIMEOUT",
"请求等待时间过长,请稍后重试。",
undefined,
{ cause: error },
);
}
throw new ApiError(
"network",
"NETWORK_UNAVAILABLE",
"暂时无法连接服务。你的操作没有被标记为成功。",
undefined,
{ cause: error },
);
} finally {
globalThis.clearTimeout(timeout);
}
},
};
}
|