-
Notifications
You must be signed in to change notification settings - Fork 22
/
index.ts
34 lines (32 loc) · 1009 Bytes
/
index.ts
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
import { CallContext, CallHandle } from "./call";
export * from "./call";
export type FetchOptions = globalThis.RequestInit & CallContext;
export function createFetch(call: CallHandle, _fetch = global.fetch) {
return async function ufetch(
input: string | Request,
init: FetchOptions,
): Promise<Response> {
const url = input.toString();
if (!url.startsWith("/")) {
return _fetch(url, init);
}
try {
const r = await call({ url, ...init });
return new Response(r.body, {
status: r.status,
statusText: r.statusText,
headers: Object.fromEntries(
Object.entries(r.headers).map(([name, value]) => [
name,
Array.isArray(value) ? value.join(",") : String(value) || "",
]),
),
});
} catch (error: any) {
return new Response(error.toString(), {
status: Number.parseInt(error.statusCode || error.code) || 500,
statusText: error.statusText,
});
}
};
}