UNPKG

2.68 kBPlain TextView Raw
1import 'isomorphic-fetch';
2
3type HttpMethod = 'GET' | 'PUT' | 'POST' | 'PATCH' | 'DELETE';
4export interface IResponse<T> {
5 ok: boolean;
6 status: number;
7 statusText?: string;
8 type: string;
9 url: string;
10 data?: T;
11}
12
13export interface IHttpHeaders {
14 [id: string]: string;
15}
16
17async function request<T>(
18 method: HttpMethod,
19 requestUrl: string,
20 data?: object,
21 headers?: IHttpHeaders,
22): Promise<IResponse<T>> {
23 const payload = {
24 method,
25 body: data ? JSON.stringify(data) : undefined,
26 headers: new Headers(),
27 };
28 if (data) {
29 payload.headers.append('Accept', 'application/json');
30 payload.headers.append('Content-Type', 'application/json');
31 }
32 if (headers) {
33 Object.assign(payload.headers, headers);
34 }
35
36 const response = await fetch(requestUrl, payload);
37 const { ok, status, statusText, type, url } = response;
38 const result = { ok, status, statusText, type, url, data: undefined };
39 if (ok) {
40 // Attempt to parse the response as JSON.
41 const contentType = (response.headers as any)._headers['content-type'];
42 if (contentType[0].startsWith('application/json')) {
43 result.data = await response.json();
44 }
45 }
46 return result;
47}
48
49function get<T>(url: string, headers?: IHttpHeaders): Promise<IResponse<T>> {
50 return request<T>('GET', url, undefined, headers);
51}
52
53function put<T>(
54 url: string,
55 data?: object,
56 headers?: IHttpHeaders,
57): Promise<IResponse<T>> {
58 return request<T>('PUT', url, data, headers);
59}
60
61function post<T>(
62 url: string,
63 data?: object,
64 headers?: IHttpHeaders,
65): Promise<IResponse<T>> {
66 return request<T>('POST', url, data, headers);
67}
68
69function patch<T>(
70 url: string,
71 data?: object,
72 headers?: IHttpHeaders,
73): Promise<IResponse<T>> {
74 return request<T>('PATCH', url, data, headers);
75}
76
77function del<T>(url: string, headers?: IHttpHeaders): Promise<IResponse<T>> {
78 return request<T>('DELETE', url, undefined, headers);
79}
80
81function headers(httpHeaders: IHttpHeaders) {
82 return {
83 get: <T>(url: string): Promise<IResponse<T>> => get<T>(url, httpHeaders),
84 put: <T>(url: string, data?: object): Promise<IResponse<T>> =>
85 put<T>(url, data, httpHeaders),
86 post: <T>(url: string, data?: object): Promise<IResponse<T>> =>
87 post<T>(url, data, httpHeaders),
88 patch: <T>(url: string, data?: object): Promise<IResponse<T>> =>
89 patch<T>(url, data, httpHeaders),
90 delete: <T>(url: string): Promise<IResponse<T>> => del<T>(url, httpHeaders),
91 headers: (append: IHttpHeaders) => headers({ ...httpHeaders, ...append }),
92 };
93}
94
95export { get, put, post, patch, del as delete, headers };
96export default { get, put, post, patch, delete: del, headers };