37 lines
988 B
TypeScript
37 lines
988 B
TypeScript
import { type Method, createFetch } from '@better-fetch/fetch';
|
|
import type { HeadersInit } from 'bun';
|
|
|
|
const apiClient = createFetch({
|
|
baseURL: 'https://api.ez-pp.farm/',
|
|
throw: true,
|
|
});
|
|
|
|
export type ApiResponse<T> = { data: T; error: undefined } | { data: undefined; error: Error };
|
|
|
|
export const fetchApi = async <T>(
|
|
route: string,
|
|
options?: {
|
|
query?: Record<string, unknown>;
|
|
headers?: HeadersInit;
|
|
method?: Method;
|
|
params?: Record<string, unknown>;
|
|
timeout?: number;
|
|
signal?: AbortSignal;
|
|
}
|
|
): Promise<ApiResponse<T>> => {
|
|
try {
|
|
const data = await apiClient<T>(route, {
|
|
query: options?.query,
|
|
headers: options?.headers ?? {
|
|
accept: 'application/json',
|
|
},
|
|
method: options?.method ?? 'GET',
|
|
params: options?.params,
|
|
timeout: options?.timeout,
|
|
signal: options?.signal,
|
|
});
|
|
return { data, error: undefined };
|
|
} catch (err) {
|
|
return { data: undefined, error: err as Error };
|
|
}
|
|
}; |