-
Notifications
You must be signed in to change notification settings - Fork 89
/
Copy pathsbFetch.ts
195 lines (163 loc) · 4.47 KB
/
sbFetch.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
import { SbHelpers } from './sbHelpers';
import type {
ISbCustomFetch,
ISbError,
ISbResponse,
ISbStoriesParams,
} from './interfaces';
import type Method from './constants';
export interface ResponseFn {
(arg?: ISbResponse | any): any;
}
export interface ISbFetch {
baseURL: string;
timeout?: number;
headers: Headers;
responseInterceptor?: ResponseFn;
fetch?: typeof fetch;
}
class SbFetch {
private baseURL: string;
private timeout?: number;
private headers: Headers;
private responseInterceptor?: ResponseFn;
private fetch: typeof fetch;
private ejectInterceptor?: boolean;
private url: string;
private parameters: ISbStoriesParams;
private fetchOptions: ISbCustomFetch;
public constructor($c: ISbFetch) {
this.baseURL = $c.baseURL;
this.headers = $c.headers || new Headers();
this.timeout = $c?.timeout ? $c.timeout * 1000 : 0;
this.responseInterceptor = $c.responseInterceptor;
this.fetch = (...args: [any]) =>
$c.fetch ? $c.fetch(...args) : fetch(...args);
this.ejectInterceptor = false;
this.url = '';
this.parameters = {} as ISbStoriesParams;
this.fetchOptions = {};
}
/**
*
* @param url string
* @param params ISbStoriesParams
* @returns Promise<ISbResponse | Error>
*/
public get(url: string, params: ISbStoriesParams) {
this.url = url;
this.parameters = params;
return this._methodHandler('get');
}
public post(url: string, params: ISbStoriesParams) {
this.url = url;
this.parameters = params;
return this._methodHandler('post');
}
public put(url: string, params: ISbStoriesParams) {
this.url = url;
this.parameters = params;
return this._methodHandler('put');
}
public delete(url: string, params?: ISbStoriesParams) {
this.url = url;
this.parameters = params ?? {} as ISbStoriesParams;
return this._methodHandler('delete');
}
private async _responseHandler(res: Response) {
const headers: string[] = [];
const response = {
data: {},
headers: {},
status: 0,
statusText: '',
};
if (res.status !== 204) {
await res.json().then(($r) => {
response.data = $r;
});
}
for (const pair of res.headers.entries()) {
headers[pair[0] as any] = pair[1];
}
response.headers = { ...headers };
response.status = res.status;
response.statusText = res.statusText;
return response;
}
private async _methodHandler(
method: Method,
): Promise<ISbResponse | ISbError> {
let urlString = `${this.baseURL}${this.url}`;
let body = null;
if (method === 'get') {
const helper = new SbHelpers();
urlString = `${this.baseURL}${this.url}?${helper.stringify(
this.parameters,
)}`;
}
else {
body = JSON.stringify(this.parameters);
}
const url = new URL(urlString);
const controller = new AbortController();
const { signal } = controller;
let timeout;
if (this.timeout) {
timeout = setTimeout(() => controller.abort(), this.timeout);
}
try {
const fetchResponse = await this.fetch(`${url}`, {
method,
headers: this.headers,
body,
signal,
...this.fetchOptions,
});
if (this.timeout) {
clearTimeout(timeout);
}
const response = (await this._responseHandler(
fetchResponse,
)) as ISbResponse;
if (this.responseInterceptor && !this.ejectInterceptor) {
return this._statusHandler(this.responseInterceptor(response));
}
else {
return this._statusHandler(response);
}
}
catch (err: any) {
const error: ISbError = {
message: err,
};
return error;
}
}
public setFetchOptions(fetchOptions: ISbCustomFetch = {}) {
if (Object.keys(fetchOptions).length > 0 && 'method' in fetchOptions) {
delete fetchOptions.method;
}
this.fetchOptions = { ...fetchOptions };
}
public eject() {
this.ejectInterceptor = true;
}
private _statusHandler(res: ISbResponse): Promise<ISbResponse | ISbError> {
const statusOk = /20[0-6]/g;
return new Promise((resolve, reject) => {
if (statusOk.test(`${res.status}`)) {
return resolve(res);
}
const error: ISbError = {
message: res.statusText,
status: res.status,
response: Array.isArray(res.data)
? res.data[0]
: res.data.error || res.data.slug,
};
reject(error);
});
}
}
export default SbFetch;