-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpclient.ts
300 lines (284 loc) · 7.83 KB
/
httpclient.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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
/**
* @module httpclient
* Description: Generic async HTTP client with middleware support for Request and Response handling.
**/
import {
createMiddlewareApi,
MiddlewareParams,
} from "../middleware";
import {
AnyObject,
TypedArray,
} from "../types";
/**
* https://developer.mozilla.org/en-US/docs/Web/API/RequestInit#body
* Name: RequestBody
* Description: Union type covering all possible RequestBody types.
* @public
* @typedef {ArrayBuffer | Blob | BodyInit | DataView | FormData | string | TypedArray | URLSearchParams} RequestBody
*/
export type RequestBody =
| ArrayBuffer
| Blob
| BodyInit
| DataView
| FormData
| string
| TypedArray
| URLSearchParams;
/**
* https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Priority
* Name: RequestPriority
* Description: Union type covering all possible RequestBody types for use with the RequestInit.
* @public
* @typedef {'auto' | 'high' | 'low'} RequestPriority
*/
export type RequestPriority =
| 'auto'
| 'high'
| 'low';
/**
* https://datatracker.ietf.org/doc/html/rfc2616#section-5.1.1
* Name: HTTPMethods
* Description: Methods supported by XMLHttpRequest or fetch.
* @public
* @enum {string}
*/
export enum HTTPMethods {
CONNECT = 'CONNECT',
DELETE = 'DELETE',
GET = 'GET',
HEAD = 'HEAD',
OPTIONS = 'OPTIONS',
PATCH = 'PATCH',
POST = 'POST',
PUT = 'PUT',
TRACE = 'TRACE',
}
/**
* https://datatracker.ietf.org/doc/html/rfc2616#section-5.1.1
* Name: HTTPMethodValues
* Description: Methods supported by XMLHttpRequest or fetch.
* @public
* @typedef {string} - Union type of HTTPMethods string values
*/
export type HTTPMethodValues = `${HTTPMethods}`;
/**
* https://developer.mozilla.org/en-US/docs/Web/API/Attribution_Reporting_API
* Name: AttributionReportingOptions
* Description: Options for attributionReporting. Experimental and might be removed.
* @public
* @typedef {Object} AttributionReportingOptions
* @property {boolean} eventsourceeligible
* @property {boolean} triggereligible
*/
export type AttributionReportingOptions = {
eventsourceeligible: boolean;
triggereligible: boolean;
};
/**
* https://developer.mozilla.org/en-US/docs/Web/API/RequestInit
* Name: RequestInit
* Description: Request used for overload of `fetch(string | URL, RequestInit)` vs. `fetch(Request)`
* @public
* @typedef {Object} RequestInit
* @property {AttributionReportingOptions} attributionReporting
* @property {RequestBody} body
* @property {boolean} browsingTopics
* @property {RequestCache} cache
* @property {RequestCredentials} credentials
* @property {Headers} headers
* @property {string} integrity
* @property {boolean} keepalive
* @property {HTTPMethods} method
* @property {RequestMode} mode
* @property {RequestPriority} priority
* @property {RequestRedirect} redirect
* @property {'' | 'about:client' | URL['href']} referrer
* @property {ReferrerPolicy} referrerPolicy
* @property {AbortSignal | null} signal
*/
export type RequestInit = {
attributionReporting?: AttributionReportingOptions;
body?: RequestBody;
browsingTopics?: boolean;
cache?: RequestCache;
credentials?: RequestCredentials;
headers?: Headers;
/**
* While integrity is not officially listed as optional,
* it has a default value of an empty string so it is technically optional.
*/
integrity?: string;
keepalive?: boolean;
method?: HTTPMethodValues;
mode?: RequestMode;
priority?: RequestPriority;
redirect?: RequestRedirect;
referrer?: '' | 'about:client' | URL['href'];
referrerPolicy?: ReferrerPolicy;
signal?: AbortSignal | null;
};
/**
* Name: FetchParams
* Description: Params type for fetch request with signature of `fetch(request, RequestInit)`
* @public
* @typedef {Object} FetchParams
* @property {Request | URL | string} request
* @property {RequestInit} options
*/
export type FetchParams = [
request:
| Request
| string
| URL,
requestInitOptions?: RequestInit,
];
/**
* Name: HTTPCLIENT_ACTIONS
* Description: HttpClient actions to be used for middleware or similar
* @public
* @readonly
* @enum {string}
*/
export enum HTTPCLIENT_ACTIONS {
HTTP_REQUEST = 'HTTP_REQUEST',
HTTP_RESPONSE = 'HTTP_RESPONSE',
}
/**
* Name: HttpClientParams
* Description: Params type for HttpClient
* @public
* @typedef {Object} HttpClientParams
* @property {Request | URL | string} request
* @property {RequestInit} options
*/
export type HttpClientParams = {
abortControllerOptions?: {
reason?: string;
timeout?: number;
};
middlewareOptions?: AnyObject;
requestInitOptions?: RequestInit;
request:
| Request
| string
| URL;
};
/**
* Name: HttpClient
* Description: fetch request factory with request and response middleware support
* Function:
* @public
* @param defaultParams HttpClientParams
* @returns {(requestInit?: RequestInit): Promise<R>} async http client
*/
export function HttpClient<R = any>(defaultParams: HttpClientParams & MiddlewareParams) {
const {
abortControllerOptions = {},
createApi,
middleware,
middlewareOptions = {},
request,
requestInitOptions = {},
sort,
transform,
} = defaultParams;
const {
reason = 'Controller was aborted.',
timeout = 5000,
} = abortControllerOptions;
let {
signal,
} = requestInitOptions;
if (!signal) {
const controller = new AbortController();
const timeoutSignal = AbortSignal.timeout(timeout);
signal = AbortSignal.any([controller.signal, timeoutSignal]);
setTimeout(() => controller.abort(reason), timeout);
}
const api = createMiddlewareApi({
createApi,
middleware,
sort,
transform,
});
return async (requestInit?: RequestInit) : Promise<R> => {
const mergedOptions = {
...requestInitOptions,
...requestInit,
};
const { requestOptions } = <{ requestOptions: FetchParams }>api({
action: {
data: {
options: middlewareOptions,
},
type: HTTPCLIENT_ACTIONS.HTTP_REQUEST,
},
})
.middleware({
requestOptions: [
request,
{
...mergedOptions,
...{ signal },
},
],
});
const result = await fetch(...requestOptions);
return api({
action: {
data: {
options: middlewareOptions,
},
type: HTTPCLIENT_ACTIONS.HTTP_RESPONSE,
},
}).middleware(result);
};
};
/**
*
* Name: clientFactory
* Description: Per method HttpClient factory
* Function:
* @public
* @param method HTTPMethods
* @param defaultParams HttpClientParams
* @returns
*/
export function clientFactory(method: HTTPMethods, defaultParams: HttpClientParams & MiddlewareParams) {
return async (params?: HttpClientParams) => {
const mergedOptions = {
...defaultParams,
...params,
};
mergedOptions.requestInitOptions = mergedOptions.requestInitOptions ?
{
...mergedOptions.requestInitOptions,
...{ method },
} :
{ method };
return HttpClient(mergedOptions);
};
};
/**
* Name: createHttpClient
* Description: Per path/resource HttpClient factory
* Function:
* @public
* @param defaultParams HttpClientParams
* @returns {Object} HTTP method factories based of default params
*/
export function createHttpClient(defaultParams: HttpClientParams & MiddlewareParams) {
return {
connect: clientFactory(HTTPMethods.CONNECT, defaultParams),
delete: clientFactory(HTTPMethods.DELETE, defaultParams),
get: clientFactory(HTTPMethods.GET, defaultParams),
head: clientFactory(HTTPMethods.HEAD, defaultParams),
options: clientFactory(HTTPMethods.OPTIONS, defaultParams),
patch: clientFactory(HTTPMethods.PATCH, defaultParams),
post: clientFactory(HTTPMethods.POST, defaultParams),
put: clientFactory(HTTPMethods.PUT, defaultParams),
trace: clientFactory(HTTPMethods.TRACE, defaultParams),
}
};