feat: 完成模板目录导入与生命周期管理
This commit is contained in:
1 parent
553a07c4ec
commit
413413efda
25 files changed
+1313
-24
No files matched your search
@@ -19,22 +19,33 @@ export interface ApiClientOptions {
|
||||
|
||||
export type RequestFn = <T>(
|
||||
path: string,
|
||||
options?: { method?: string; body?: unknown },
|
||||
options?: { method?: string; body?: unknown; rawBody?: unknown },
|
||||
) => Promise<T>;
|
||||
|
||||
export async function request<T>(
|
||||
state: { baseUrl: string; fetcher: FetchLike; token?: string | undefined },
|
||||
path: string,
|
||||
options: { method?: string; body?: unknown } = {},
|
||||
options: { method?: string; body?: unknown; rawBody?: unknown } = {},
|
||||
): Promise<T> {
|
||||
const headers: Record<string, string> = { accept: "application/json" };
|
||||
if (options.body !== undefined) headers["content-type"] = "application/json";
|
||||
if (options.rawBody === undefined && options.body !== undefined)
|
||||
headers["content-type"] = "application/json";
|
||||
if (state.token) headers.authorization = `Bearer ${state.token}`;
|
||||
const response = await state.fetcher(`${state.baseUrl}${path}`, {
|
||||
const init = {
|
||||
method: options.method ?? "GET",
|
||||
headers,
|
||||
...(options.body === undefined ? {} : { body: JSON.stringify(options.body) }),
|
||||
});
|
||||
...(options.rawBody !== undefined
|
||||
? { body: options.rawBody }
|
||||
: options.body === undefined
|
||||
? {}
|
||||
: { body: JSON.stringify(options.body) }),
|
||||
};
|
||||
const response = await (
|
||||
state.fetcher as unknown as (
|
||||
input: string,
|
||||
init?: { method?: string; headers?: Record<string, string>; body?: unknown },
|
||||
) => Promise<FetchResponse>
|
||||
)(`${state.baseUrl}${path}`, init);
|
||||
const body = await response.json();
|
||||
if (!response.ok) throw new ApiClientError(response.status, body as ApiErrorBody);
|
||||
return body as T;
|
||||
|
||||
Reference in new issue
Block a user