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 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 | 14x 14x 14x 14x 14x 65x 2x 26x 26x 26x 64x 64x 64x 64x 64x 66x 66x 66x 66x 66x 27x 66x 66x 12x 54x 66x 66x 65x 65x 65x 6x 6x 4x 3x 2x 2x 3x 59x 59x 5x 4x 1x 1x 66x | 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;
requestAuthorityProvider?: () => string | null;
onUnauthorized?: UnauthorizedHandler;
}
export interface UnauthorizedRequestContext {
path: string;
method: string;
accessToken: string | null;
requestAuthority: string | null;
retryAttempted: boolean;
}
export type UnauthorizedHandler = (
context: UnauthorizedRequestContext,
) => Promise<"retry" | "reject">;
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,
);
}
function hasReplayableBody(body: BodyInit | null | undefined): boolean {
return body == null
|| typeof ReadableStream === "undefined"
|| !(body instanceof ReadableStream);
}
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 timeoutMs = requestOptions.timeoutMs ?? defaultTimeoutMs;
const method = requestOptions.method?.toUpperCase() ?? "GET";
const requestAuthority = options.requestAuthorityProvider?.() ?? null;
let retryAttempted = false;
while (true) {
const controller = new AbortController();
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?.() ?? null;
if (token) {
headers.set("Authorization", `Bearer ${token}`);
} else Iif (options.tokenProvider) {
headers.delete("Authorization");
}
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) {
const error = new ApiError(
"http",
payload.code || `HTTP_${response.status}`,
payload.message || "请求未完成。",
response.status,
);
if (
response.status === 401
&& payload.code === "UNAUTHORIZED"
&& options.onUnauthorized
) {
const action = await options.onUnauthorized({
path,
method,
accessToken: token,
requestAuthority,
retryAttempted,
});
if (
action === "retry"
&& !retryAttempted
&& hasReplayableBody(requestOptions.body)
) {
retryAttempted = true;
continue;
}
}
throw error;
}
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);
}
}
},
};
}
|