refactor: 拆分 API Client 资源模块
This commit is contained in:
1 parent
f3adf7bc15
commit
357f271639
24 files changed
+1280
-905
No files matched your search
@@ -0,0 +1,59 @@
|
||||
import type { ApiErrorBody } from "../types/common.js";
|
||||
|
||||
export interface FetchResponse {
|
||||
readonly status: number;
|
||||
readonly ok: boolean;
|
||||
json(): Promise<unknown>;
|
||||
}
|
||||
|
||||
export type FetchLike = (
|
||||
input: string,
|
||||
init?: { method?: string; headers?: Record<string, string>; body?: string },
|
||||
) => Promise<FetchResponse>;
|
||||
|
||||
export interface ApiClientOptions {
|
||||
baseUrl: string;
|
||||
fetcher: FetchLike;
|
||||
token?: string;
|
||||
}
|
||||
|
||||
export type RequestFn = <T>(
|
||||
path: string,
|
||||
options?: { method?: string; body?: unknown },
|
||||
) => Promise<T>;
|
||||
|
||||
export async function request<T>(
|
||||
state: { baseUrl: string; fetcher: FetchLike; token?: string | undefined },
|
||||
path: string,
|
||||
options: { method?: string; body?: unknown } = {},
|
||||
): Promise<T> {
|
||||
const headers: Record<string, string> = { accept: "application/json" };
|
||||
if (options.body !== undefined) headers["content-type"] = "application/json";
|
||||
if (state.token) headers.authorization = `Bearer ${state.token}`;
|
||||
const response = await state.fetcher(`${state.baseUrl}${path}`, {
|
||||
method: options.method ?? "GET",
|
||||
headers,
|
||||
...(options.body === undefined ? {} : { body: JSON.stringify(options.body) }),
|
||||
});
|
||||
const body = await response.json();
|
||||
if (!response.ok) throw new ApiClientError(response.status, body as ApiErrorBody);
|
||||
return body as T;
|
||||
}
|
||||
|
||||
export class ApiClientError extends Error {
|
||||
constructor(
|
||||
readonly status: number,
|
||||
readonly body: ApiErrorBody,
|
||||
) {
|
||||
super(body.error.message);
|
||||
this.name = "ApiClientError";
|
||||
}
|
||||
|
||||
get code(): string {
|
||||
return this.body.error.code;
|
||||
}
|
||||
|
||||
get requestId(): string | null {
|
||||
return this.body.requestId;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user