-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.ts
43 lines (37 loc) · 1.19 KB
/
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
35
36
37
38
39
40
41
42
43
import { RequestContext } from './request-context';
import { ResponseContext } from './response-context';
import { BaseFetcherData } from './types';
export * from './types';
export { RequestContext, ResponseContext };
export interface Fetcher<T extends BaseFetcherData> {
send(request: RequestContext, options?: T): Promise<ResponseContext>;
}
export class IsomorphicFetchHttpLibrary<
T extends BaseFetcherData = BaseFetcherData,
> implements Fetcher<T>
{
public async send(
request: RequestContext,
options: T,
): Promise<ResponseContext> {
const method = request.getHttpMethod().toString();
const body = request.getBody();
const resp = await fetch(request.getUrl(), {
credentials: 'same-origin',
headers: request.getHeaders(),
...options,
// Method, URL and Body can't be overridden in this fetcher implementation
method,
body,
});
const headers: Record<string, string> = {};
resp.headers.forEach((value: string, name: string) => {
headers[name] = value;
});
return new ResponseContext(resp.status, headers, {
text: () => resp.text(),
binary: () => resp.blob(),
json: () => resp.json(),
});
}
}