import { request } from 'undici'; import type { Dispatcher } from 'undici'; export type HttpApiOptions = { headers?: HeadersInit; body?: string; method?: Dispatcher.HttpMethod; }; export type HttpApiFetch = (url: string, ops?: HttpApiOptions) => Promise; export function useHttpApi(event: H3Event, token?: string): HttpApiFetch { const config = useRuntimeConfig(event); async function httpFetch(url: string, opts: HttpApiOptions = {}): Promise { const headers = new Headers(opts.headers); headers.set('Host', config.apiBaseHost); // Can't use fetch due to Host header overwriting if (token) { headers.set('Authorization', `Bearer ${token}`); } const urlWithBase = new URL(url, config.apiBase); const response = await request(urlWithBase, { method: opts.method, headers: Object.fromEntries(headers.entries()), body: opts?.body }); if (response.statusCode >= 400) { const err = new Error(`Request failed with ${response.statusCode}`); try { (err as any).data = await response.body.text(); } catch { // It's already errored, we don't need to know the body } throw err; } return await response.body.json() as T; } return httpFetch; }