@hyper-fetch/core 3.3.3 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/index.cjs.js +1 -1
- package/dist/browser/index.cjs.js.map +4 -4
- package/dist/browser/index.esm.js +1 -1
- package/dist/browser/index.esm.js.map +4 -4
- package/dist/index.cjs.js +1 -1
- package/dist/index.cjs.js.map +4 -4
- package/dist/index.d.ts +330 -180
- package/dist/index.esm.js +1 -1
- package/dist/index.esm.js.map +4 -4
- package/package.json +4 -2
- package/src/adapter/adapter.bindings.ts +124 -35
- package/src/adapter/adapter.browser.ts +29 -25
- package/src/adapter/adapter.server.ts +81 -81
- package/src/adapter/adapter.ts +1 -6
- package/src/adapter/adapter.types.ts +100 -12
- package/src/adapter/adapter.utils.ts +16 -23
- package/src/cache/cache.events.ts +9 -6
- package/src/cache/cache.ts +37 -30
- package/src/cache/cache.types.ts +32 -15
- package/src/cache/cache.utils.ts +7 -9
- package/src/client/client.constants.ts +6 -0
- package/src/client/client.ts +130 -59
- package/src/client/client.types.ts +11 -10
- package/src/client/client.utils.ts +20 -6
- package/src/dispatcher/dispatcher.ts +20 -26
- package/src/dispatcher/dispatcher.types.ts +4 -4
- package/src/dispatcher/dispatcher.utils.ts +2 -11
- package/src/effect/request.effect.ts +8 -5
- package/src/effect/request.effect.types.ts +14 -5
- package/src/index.ts +1 -0
- package/src/managers/logger/logger.manager.ts +8 -8
- package/src/managers/logger/logger.manager.types.ts +5 -8
- package/src/managers/logger/logger.manager.utils.ts +2 -2
- package/src/managers/request/request.manager.events.ts +7 -7
- package/src/managers/request/request.manager.types.ts +0 -1
- package/src/mocker/index.ts +2 -0
- package/src/mocker/mocker.ts +96 -0
- package/src/mocker/mocker.types.ts +26 -0
- package/src/request/request.ts +227 -224
- package/src/request/request.types.ts +75 -35
- package/src/request/request.utils.ts +61 -28
- package/src/types/client.types.ts +4 -0
- package/src/types/fetch.types.ts +16 -25
- package/src/types/http.types.ts +1 -0
- package/src/types/index.ts +1 -0
- package/{tsconfig.node.json → tsconfig.base.json} +3 -3
- package/tsconfig.json +3 -4
- package/dist/server/index.cjs.js +0 -2
- package/dist/server/index.cjs.js.map +0 -7
- package/dist/server/index.esm.js +0 -2
- package/dist/server/index.esm.js.map +0 -7
package/src/client/client.ts
CHANGED
|
@@ -1,38 +1,43 @@
|
|
|
1
1
|
import {
|
|
2
|
-
AdapterType,
|
|
3
2
|
adapter as defaultAdapter,
|
|
4
|
-
|
|
5
|
-
ResponseType,
|
|
6
|
-
QueryParamsType,
|
|
7
|
-
QueryStringifyOptionsType,
|
|
8
|
-
HeaderMappingType,
|
|
3
|
+
AdapterInstance,
|
|
9
4
|
AdapterPayloadMappingType,
|
|
5
|
+
AdapterType,
|
|
6
|
+
ExtractAdapterExtraType,
|
|
7
|
+
ExtractAdapterMethodType,
|
|
8
|
+
ExtractAdapterOptionsType,
|
|
9
|
+
ExtractAdapterQueryParamsType,
|
|
10
|
+
ExtractUnionAdapter,
|
|
11
|
+
HeaderMappingType,
|
|
12
|
+
QueryStringifyOptionsType,
|
|
13
|
+
ResponseReturnType,
|
|
10
14
|
} from "adapter";
|
|
11
15
|
import {
|
|
12
|
-
|
|
16
|
+
xhrExtra,
|
|
17
|
+
ClientErrorType,
|
|
18
|
+
ClientInstance,
|
|
19
|
+
ClientOptionsType,
|
|
13
20
|
getAdapterHeaders,
|
|
14
21
|
getAdapterPayload,
|
|
15
|
-
ClientOptionsType,
|
|
16
|
-
ClientInstance,
|
|
17
|
-
ClientErrorType,
|
|
18
|
-
StringifyCallbackType,
|
|
19
22
|
RequestInterceptorType,
|
|
20
23
|
ResponseInterceptorType,
|
|
24
|
+
StringifyCallbackType,
|
|
25
|
+
stringifyQueryParams,
|
|
21
26
|
} from "client";
|
|
22
27
|
import { Cache } from "cache";
|
|
23
28
|
import { Dispatcher } from "dispatcher";
|
|
24
29
|
import { RequestEffectInstance } from "effect";
|
|
25
|
-
import {
|
|
26
|
-
import { AppManager,
|
|
30
|
+
import { getRequestKey, getSimpleKey, Request, RequestInstance, RequestOptionsType } from "request";
|
|
31
|
+
import { AppManager, LoggerManager, RequestManager, SeverityType } from "managers";
|
|
27
32
|
import { interceptRequest, interceptResponse } from "./client.utils";
|
|
33
|
+
import { HttpMethodsEnum } from "../constants/http.constants";
|
|
28
34
|
|
|
29
35
|
/**
|
|
30
36
|
* **Client** is a class that allows you to configure the connection with the server and then use it to create
|
|
31
37
|
* requests which, when called using the appropriate method, will cause the server to be queried for the endpoint and
|
|
32
38
|
* method specified in the request.
|
|
33
|
-
* @position 1
|
|
34
39
|
*/
|
|
35
|
-
export class Client<GlobalErrorType extends ClientErrorType = Error,
|
|
40
|
+
export class Client<GlobalErrorType extends ClientErrorType = Error, Adapter extends AdapterInstance = AdapterType> {
|
|
36
41
|
readonly url: string;
|
|
37
42
|
public debug: boolean;
|
|
38
43
|
|
|
@@ -49,20 +54,27 @@ export class Client<GlobalErrorType extends ClientErrorType = Error, AdapterOpti
|
|
|
49
54
|
loggerManager: LoggerManager = new LoggerManager(this);
|
|
50
55
|
|
|
51
56
|
// Config
|
|
52
|
-
adapter:
|
|
53
|
-
cache: Cache
|
|
57
|
+
adapter: Adapter;
|
|
58
|
+
cache: Cache<this>;
|
|
54
59
|
fetchDispatcher: Dispatcher;
|
|
55
60
|
submitDispatcher: Dispatcher;
|
|
56
61
|
|
|
62
|
+
defaultMethod: ExtractAdapterMethodType<Adapter> = HttpMethodsEnum.get as ExtractAdapterMethodType<Adapter>;
|
|
63
|
+
defaultExtra: ExtractAdapterExtraType<Adapter> = xhrExtra as ExtractAdapterExtraType<Adapter>;
|
|
64
|
+
|
|
57
65
|
// Registered requests effect
|
|
58
66
|
effects: RequestEffectInstance[] = [];
|
|
59
67
|
|
|
60
68
|
// Options
|
|
61
69
|
queryParamsConfig?: QueryStringifyOptionsType;
|
|
62
|
-
adapterDefaultOptions?: (request: RequestInstance) =>
|
|
70
|
+
adapterDefaultOptions?: (request: RequestInstance) => ExtractAdapterOptionsType<Adapter>;
|
|
63
71
|
requestDefaultOptions?: (
|
|
64
|
-
options: RequestOptionsType<string,
|
|
65
|
-
) => Partial<RequestOptionsType<string,
|
|
72
|
+
options: RequestOptionsType<string, ExtractAdapterOptionsType<Adapter>, ExtractAdapterMethodType<Adapter>>,
|
|
73
|
+
) => Partial<RequestOptionsType<string, ExtractAdapterOptionsType<Adapter>, ExtractAdapterMethodType<Adapter>>>;
|
|
74
|
+
abortKeyMapper?: (request: RequestInstance) => string = getSimpleKey;
|
|
75
|
+
cacheKeyMapper?: (request: RequestInstance) => string = getRequestKey;
|
|
76
|
+
queueKeyMapper?: (request: RequestInstance) => string = getSimpleKey;
|
|
77
|
+
effectKeyMapper?: (request: RequestInstance) => string = getSimpleKey;
|
|
66
78
|
|
|
67
79
|
// Utils
|
|
68
80
|
|
|
@@ -83,14 +95,14 @@ export class Client<GlobalErrorType extends ClientErrorType = Error, AdapterOpti
|
|
|
83
95
|
// Logger
|
|
84
96
|
logger = this.loggerManager.init("Client");
|
|
85
97
|
|
|
86
|
-
constructor(public options: ClientOptionsType) {
|
|
98
|
+
constructor(public options: ClientOptionsType<Client<GlobalErrorType, Adapter>>) {
|
|
87
99
|
const { url, adapter, appManager, cache, fetchDispatcher, submitDispatcher } = this.options;
|
|
88
100
|
this.url = url;
|
|
89
|
-
this.adapter = adapter || defaultAdapter;
|
|
101
|
+
this.adapter = (adapter || defaultAdapter) as Adapter;
|
|
90
102
|
|
|
91
103
|
// IMPORTANT: Do not change initialization order as it's crucial for dependencies injection
|
|
92
104
|
this.appManager = appManager?.(this) || new AppManager();
|
|
93
|
-
this.cache = cache?.(this) || new Cache(this)
|
|
105
|
+
this.cache = (cache?.(this) || new Cache(this)) as Cache<this>;
|
|
94
106
|
this.fetchDispatcher = fetchDispatcher?.(this) || new Dispatcher(this);
|
|
95
107
|
this.submitDispatcher = submitDispatcher?.(this) || new Dispatcher(this);
|
|
96
108
|
}
|
|
@@ -99,15 +111,17 @@ export class Client<GlobalErrorType extends ClientErrorType = Error, AdapterOpti
|
|
|
99
111
|
* This method allows to configure global defaults for the request configuration like method, auth, deduplication etc.
|
|
100
112
|
*/
|
|
101
113
|
setRequestDefaultOptions = (
|
|
102
|
-
callback: (
|
|
103
|
-
|
|
114
|
+
callback: (
|
|
115
|
+
request: RequestInstance,
|
|
116
|
+
) => Partial<RequestOptionsType<string, ExtractAdapterOptionsType<Adapter>, ExtractAdapterMethodType<Adapter>>>,
|
|
117
|
+
): Client<GlobalErrorType, Adapter> => {
|
|
104
118
|
this.requestDefaultOptions = callback;
|
|
105
119
|
return this;
|
|
106
120
|
};
|
|
107
121
|
|
|
108
122
|
setAdapterDefaultOptions = (
|
|
109
|
-
callback: (request: RequestInstance) =>
|
|
110
|
-
): Client<GlobalErrorType,
|
|
123
|
+
callback: (request: RequestInstance) => ExtractAdapterOptionsType<Adapter>,
|
|
124
|
+
): Client<GlobalErrorType, Adapter> => {
|
|
111
125
|
this.adapterDefaultOptions = callback;
|
|
112
126
|
return this;
|
|
113
127
|
};
|
|
@@ -115,7 +129,7 @@ export class Client<GlobalErrorType extends ClientErrorType = Error, AdapterOpti
|
|
|
115
129
|
/**
|
|
116
130
|
* This method enables the logger usage and display the logs in console
|
|
117
131
|
*/
|
|
118
|
-
setDebug = (debug: boolean): Client<GlobalErrorType,
|
|
132
|
+
setDebug = (debug: boolean): Client<GlobalErrorType, Adapter> => {
|
|
119
133
|
this.debug = debug;
|
|
120
134
|
return this;
|
|
121
135
|
};
|
|
@@ -123,7 +137,7 @@ export class Client<GlobalErrorType extends ClientErrorType = Error, AdapterOpti
|
|
|
123
137
|
/**
|
|
124
138
|
* Set the logger severity of the messages displayed to the console
|
|
125
139
|
*/
|
|
126
|
-
setLoggerSeverity = (severity: SeverityType): Client<GlobalErrorType,
|
|
140
|
+
setLoggerSeverity = (severity: SeverityType): Client<GlobalErrorType, Adapter> => {
|
|
127
141
|
this.loggerManager.setSeverity(severity);
|
|
128
142
|
return this;
|
|
129
143
|
};
|
|
@@ -131,7 +145,7 @@ export class Client<GlobalErrorType extends ClientErrorType = Error, AdapterOpti
|
|
|
131
145
|
/**
|
|
132
146
|
* Set the new logger instance to the Client
|
|
133
147
|
*/
|
|
134
|
-
setLogger = (callback: (Client: ClientInstance) => LoggerManager): Client<GlobalErrorType,
|
|
148
|
+
setLogger = (callback: (Client: ClientInstance) => LoggerManager): Client<GlobalErrorType, Adapter> => {
|
|
135
149
|
this.loggerManager = callback(this);
|
|
136
150
|
return this;
|
|
137
151
|
};
|
|
@@ -139,7 +153,7 @@ export class Client<GlobalErrorType extends ClientErrorType = Error, AdapterOpti
|
|
|
139
153
|
/**
|
|
140
154
|
* Set config for the query params stringify method, we can set here, among others, arrayFormat, skipNull, encode, skipEmptyString and more
|
|
141
155
|
*/
|
|
142
|
-
setQueryParamsConfig = (queryParamsConfig: QueryStringifyOptionsType): Client<GlobalErrorType,
|
|
156
|
+
setQueryParamsConfig = (queryParamsConfig: QueryStringifyOptionsType): Client<GlobalErrorType, Adapter> => {
|
|
143
157
|
this.queryParamsConfig = queryParamsConfig;
|
|
144
158
|
return this;
|
|
145
159
|
};
|
|
@@ -148,7 +162,7 @@ export class Client<GlobalErrorType extends ClientErrorType = Error, AdapterOpti
|
|
|
148
162
|
* Set the custom query params stringify method to the Client
|
|
149
163
|
* @param stringifyFn Custom callback handling query params stringify
|
|
150
164
|
*/
|
|
151
|
-
setStringifyQueryParams = (stringifyFn: StringifyCallbackType): Client<GlobalErrorType,
|
|
165
|
+
setStringifyQueryParams = (stringifyFn: StringifyCallbackType): Client<GlobalErrorType, Adapter> => {
|
|
152
166
|
this.stringifyQueryParams = stringifyFn;
|
|
153
167
|
return this;
|
|
154
168
|
};
|
|
@@ -156,7 +170,7 @@ export class Client<GlobalErrorType extends ClientErrorType = Error, AdapterOpti
|
|
|
156
170
|
/**
|
|
157
171
|
* Set the custom header mapping function
|
|
158
172
|
*/
|
|
159
|
-
setHeaderMapper = (headerMapper: HeaderMappingType): Client<GlobalErrorType,
|
|
173
|
+
setHeaderMapper = (headerMapper: HeaderMappingType): Client<GlobalErrorType, Adapter> => {
|
|
160
174
|
this.headerMapper = headerMapper;
|
|
161
175
|
return this;
|
|
162
176
|
};
|
|
@@ -164,23 +178,41 @@ export class Client<GlobalErrorType extends ClientErrorType = Error, AdapterOpti
|
|
|
164
178
|
/**
|
|
165
179
|
* Set the request payload mapping function which get triggered before request get send
|
|
166
180
|
*/
|
|
167
|
-
setPayloadMapper = (payloadMapper: AdapterPayloadMappingType): Client<GlobalErrorType,
|
|
181
|
+
setPayloadMapper = (payloadMapper: AdapterPayloadMappingType): Client<GlobalErrorType, Adapter> => {
|
|
168
182
|
this.payloadMapper = payloadMapper;
|
|
169
183
|
return this;
|
|
170
184
|
};
|
|
171
185
|
|
|
172
186
|
/**
|
|
173
|
-
* Set custom http adapter to handle graphql, rest, firebase or
|
|
187
|
+
* Set custom http adapter to handle graphql, rest, firebase or others
|
|
174
188
|
*/
|
|
175
|
-
setAdapter =
|
|
176
|
-
|
|
177
|
-
|
|
189
|
+
setAdapter = <NewAdapter extends AdapterInstance>(
|
|
190
|
+
callback: (Client: ClientInstance) => NewAdapter,
|
|
191
|
+
): Client<GlobalErrorType, NewAdapter> => {
|
|
192
|
+
this.adapter = callback(this) as unknown as Adapter;
|
|
193
|
+
return this as unknown as Client<GlobalErrorType, NewAdapter>;
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Set default method for requests.
|
|
198
|
+
*/
|
|
199
|
+
setDefaultMethod = (defaultMethod: ExtractAdapterMethodType<Adapter>) => {
|
|
200
|
+
this.defaultMethod = defaultMethod;
|
|
201
|
+
return this as ClientInstance;
|
|
202
|
+
};
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Set default additional data for initial state.
|
|
206
|
+
*/
|
|
207
|
+
setDefaultExtra = (defaultExtra: ExtractAdapterExtraType<Adapter>) => {
|
|
208
|
+
this.defaultExtra = defaultExtra;
|
|
209
|
+
return this as ClientInstance;
|
|
178
210
|
};
|
|
179
211
|
|
|
180
212
|
/**
|
|
181
213
|
* Method of manipulating requests before sending the request. We can for example add custom header with token to the request which request had the auth set to true.
|
|
182
214
|
*/
|
|
183
|
-
onAuth = (callback: RequestInterceptorType): Client<GlobalErrorType,
|
|
215
|
+
onAuth = (callback: RequestInterceptorType): Client<GlobalErrorType, Adapter> => {
|
|
184
216
|
this.__onAuthCallbacks.push(callback);
|
|
185
217
|
return this;
|
|
186
218
|
};
|
|
@@ -189,8 +221,8 @@ export class Client<GlobalErrorType extends ClientErrorType = Error, AdapterOpti
|
|
|
189
221
|
* Method for intercepting error responses. It can be used for example to refresh tokens.
|
|
190
222
|
*/
|
|
191
223
|
onError = <ErrorType = null>(
|
|
192
|
-
callback: ResponseInterceptorType<any, ErrorType | GlobalErrorType>,
|
|
193
|
-
): Client<GlobalErrorType,
|
|
224
|
+
callback: ResponseInterceptorType<any, ErrorType | GlobalErrorType, Adapter>,
|
|
225
|
+
): Client<GlobalErrorType, Adapter> => {
|
|
194
226
|
this.__onErrorCallbacks.push(callback);
|
|
195
227
|
return this;
|
|
196
228
|
};
|
|
@@ -199,8 +231,8 @@ export class Client<GlobalErrorType extends ClientErrorType = Error, AdapterOpti
|
|
|
199
231
|
* Method for intercepting success responses.
|
|
200
232
|
*/
|
|
201
233
|
onSuccess = <ErrorType = null>(
|
|
202
|
-
callback: ResponseInterceptorType<any, ErrorType | GlobalErrorType>,
|
|
203
|
-
): Client<GlobalErrorType,
|
|
234
|
+
callback: ResponseInterceptorType<any, ErrorType | GlobalErrorType, Adapter>,
|
|
235
|
+
): Client<GlobalErrorType, Adapter> => {
|
|
204
236
|
this.__onSuccessCallbacks.push(callback);
|
|
205
237
|
return this;
|
|
206
238
|
};
|
|
@@ -208,7 +240,7 @@ export class Client<GlobalErrorType extends ClientErrorType = Error, AdapterOpti
|
|
|
208
240
|
/**
|
|
209
241
|
* Method of manipulating requests before sending the request.
|
|
210
242
|
*/
|
|
211
|
-
onRequest = (callback: RequestInterceptorType): Client<GlobalErrorType,
|
|
243
|
+
onRequest = (callback: RequestInterceptorType): Client<GlobalErrorType, Adapter> => {
|
|
212
244
|
this.__onRequestCallbacks.push(callback);
|
|
213
245
|
return this;
|
|
214
246
|
};
|
|
@@ -217,8 +249,8 @@ export class Client<GlobalErrorType extends ClientErrorType = Error, AdapterOpti
|
|
|
217
249
|
* Method for intercepting any responses.
|
|
218
250
|
*/
|
|
219
251
|
onResponse = <ErrorType = null>(
|
|
220
|
-
callback: ResponseInterceptorType<any, ErrorType | GlobalErrorType>,
|
|
221
|
-
): Client<GlobalErrorType,
|
|
252
|
+
callback: ResponseInterceptorType<any, ErrorType | GlobalErrorType, Adapter>,
|
|
253
|
+
): Client<GlobalErrorType, Adapter> => {
|
|
222
254
|
this.__onResponseCallbacks.push(callback);
|
|
223
255
|
return this;
|
|
224
256
|
};
|
|
@@ -242,6 +274,23 @@ export class Client<GlobalErrorType extends ClientErrorType = Error, AdapterOpti
|
|
|
242
274
|
return this;
|
|
243
275
|
};
|
|
244
276
|
|
|
277
|
+
/**
|
|
278
|
+
* Key setters
|
|
279
|
+
*/
|
|
280
|
+
|
|
281
|
+
setAbortKeyMapper = (callback: (request: RequestInstance) => string) => {
|
|
282
|
+
this.abortKeyMapper = callback;
|
|
283
|
+
};
|
|
284
|
+
setCacheKeyMapper = (callback: (request: RequestInstance) => string) => {
|
|
285
|
+
this.cacheKeyMapper = callback;
|
|
286
|
+
};
|
|
287
|
+
setQueueKeyMapper = (callback: (request: RequestInstance) => string) => {
|
|
288
|
+
this.queueKeyMapper = callback;
|
|
289
|
+
};
|
|
290
|
+
setEffectKeyMapper = (callback: (request: RequestInstance) => string) => {
|
|
291
|
+
this.effectKeyMapper = callback;
|
|
292
|
+
};
|
|
293
|
+
|
|
245
294
|
/**
|
|
246
295
|
* Helper used by http adapter to apply the modifications on response error
|
|
247
296
|
*/
|
|
@@ -255,20 +304,24 @@ export class Client<GlobalErrorType extends ClientErrorType = Error, AdapterOpti
|
|
|
255
304
|
/**
|
|
256
305
|
* Private helper to run async on-error response processing
|
|
257
306
|
*/
|
|
258
|
-
__modifyErrorResponse = async (
|
|
259
|
-
|
|
307
|
+
__modifyErrorResponse = async (
|
|
308
|
+
response: ResponseReturnType<any, GlobalErrorType, Adapter>,
|
|
309
|
+
request: RequestInstance,
|
|
310
|
+
) => interceptResponse<GlobalErrorType, Adapter>(this.__onErrorCallbacks, response, request);
|
|
260
311
|
|
|
261
312
|
/**
|
|
262
313
|
* Private helper to run async on-success response processing
|
|
263
314
|
*/
|
|
264
|
-
__modifySuccessResponse = async (
|
|
265
|
-
|
|
315
|
+
__modifySuccessResponse = async (
|
|
316
|
+
response: ResponseReturnType<any, GlobalErrorType, Adapter>,
|
|
317
|
+
request: RequestInstance,
|
|
318
|
+
) => interceptResponse<GlobalErrorType, Adapter>(this.__onSuccessCallbacks, response, request);
|
|
266
319
|
|
|
267
320
|
/**
|
|
268
321
|
* Private helper to run async response processing
|
|
269
322
|
*/
|
|
270
|
-
__modifyResponse = async (response:
|
|
271
|
-
interceptResponse<GlobalErrorType>(this.__onResponseCallbacks, response, request);
|
|
323
|
+
__modifyResponse = async (response: ResponseReturnType<any, GlobalErrorType, Adapter>, request: RequestInstance) =>
|
|
324
|
+
interceptResponse<GlobalErrorType, Adapter>(this.__onResponseCallbacks, response, request);
|
|
272
325
|
|
|
273
326
|
/**
|
|
274
327
|
* Clears the Client instance and remove all listeners on it's dependencies
|
|
@@ -287,7 +340,7 @@ export class Client<GlobalErrorType extends ClientErrorType = Error, AdapterOpti
|
|
|
287
340
|
this.cache.emitter.removeAllListeners();
|
|
288
341
|
|
|
289
342
|
this.appManager = appManager?.(this) || new AppManager();
|
|
290
|
-
this.cache = cache?.(this) || new Cache(this)
|
|
343
|
+
this.cache = (cache?.(this) || new Cache(this)) as Cache<this>;
|
|
291
344
|
this.fetchDispatcher = fetchDispatcher?.(this) || new Dispatcher(this);
|
|
292
345
|
this.submitDispatcher = submitDispatcher?.(this) || new Dispatcher(this);
|
|
293
346
|
};
|
|
@@ -299,12 +352,30 @@ export class Client<GlobalErrorType extends ClientErrorType = Error, AdapterOpti
|
|
|
299
352
|
Response,
|
|
300
353
|
Payload = undefined,
|
|
301
354
|
LocalError extends ClientErrorType | undefined = undefined,
|
|
302
|
-
QueryParams
|
|
355
|
+
QueryParams = ExtractAdapterQueryParamsType<Adapter>,
|
|
303
356
|
>() => {
|
|
304
|
-
return <
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
357
|
+
return <
|
|
358
|
+
EndpointType extends string,
|
|
359
|
+
AdapterOptions extends ExtractAdapterOptionsType<Adapter>,
|
|
360
|
+
MethodType extends ExtractAdapterMethodType<Adapter>,
|
|
361
|
+
>(
|
|
362
|
+
params: RequestOptionsType<EndpointType, AdapterOptions, MethodType>,
|
|
363
|
+
) =>
|
|
364
|
+
new Request<
|
|
365
|
+
Response,
|
|
366
|
+
Payload,
|
|
367
|
+
QueryParams,
|
|
368
|
+
GlobalErrorType,
|
|
369
|
+
LocalError,
|
|
370
|
+
EndpointType,
|
|
371
|
+
ExtractUnionAdapter<
|
|
372
|
+
Adapter,
|
|
373
|
+
{
|
|
374
|
+
method: MethodType;
|
|
375
|
+
options: AdapterOptions;
|
|
376
|
+
queryParams: QueryParams;
|
|
377
|
+
}
|
|
378
|
+
>
|
|
379
|
+
>(this as any, params);
|
|
309
380
|
};
|
|
310
381
|
}
|
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
import { RequestInstance } from "request";
|
|
2
|
-
import {
|
|
2
|
+
import { ResponseReturnType, AdapterType, QueryParamsType, AdapterInstance } from "adapter";
|
|
3
3
|
import { Client } from "client";
|
|
4
4
|
import { NegativeTypes } from "types";
|
|
5
5
|
|
|
6
6
|
export type ClientErrorType = Record<string, any> | string;
|
|
7
|
-
export type ClientInstance = Client<any, any
|
|
7
|
+
export type ClientInstance = Client<any, AdapterType<any, any, any, any>>;
|
|
8
|
+
export type ExtractAdapterTypeFromClient<T> = T extends Client<any, infer A> ? A : never;
|
|
8
9
|
|
|
9
10
|
/**
|
|
10
11
|
* Configuration setup for the client
|
|
11
12
|
*/
|
|
12
|
-
export type ClientOptionsType = {
|
|
13
|
+
export type ClientOptionsType<C extends ClientInstance> = {
|
|
13
14
|
/**
|
|
14
15
|
* Url to your server
|
|
15
16
|
*/
|
|
@@ -21,28 +22,28 @@ export type ClientOptionsType = {
|
|
|
21
22
|
/**
|
|
22
23
|
* Custom cache initialization prop
|
|
23
24
|
*/
|
|
24
|
-
cache?:
|
|
25
|
+
cache?: (client: C) => C["cache"];
|
|
25
26
|
/**
|
|
26
27
|
* Custom app manager initialization prop
|
|
27
28
|
*/
|
|
28
|
-
appManager?:
|
|
29
|
+
appManager?: (client: C) => C["appManager"];
|
|
29
30
|
/**
|
|
30
31
|
* Custom fetch dispatcher initialization prop
|
|
31
32
|
*/
|
|
32
|
-
fetchDispatcher?:
|
|
33
|
+
fetchDispatcher?: (client: C) => C["submitDispatcher"];
|
|
33
34
|
/**
|
|
34
35
|
* Custom submit dispatcher initialization prop
|
|
35
36
|
*/
|
|
36
|
-
submitDispatcher?:
|
|
37
|
+
submitDispatcher?: (client: C) => C["fetchDispatcher"];
|
|
37
38
|
};
|
|
38
39
|
|
|
39
40
|
// Interceptors
|
|
40
41
|
|
|
41
42
|
export type RequestInterceptorType = (request: RequestInstance) => Promise<RequestInstance> | RequestInstance;
|
|
42
|
-
export type ResponseInterceptorType<Response = any, Error = any> = (
|
|
43
|
-
response:
|
|
43
|
+
export type ResponseInterceptorType<Response = any, Error = any, Adapter extends AdapterInstance = AdapterType> = (
|
|
44
|
+
response: ResponseReturnType<Response, Error, Adapter>,
|
|
44
45
|
request: RequestInstance,
|
|
45
|
-
) => Promise<
|
|
46
|
+
) => Promise<ResponseReturnType<any, any, Adapter>> | ResponseReturnType<any, any, Adapter>;
|
|
46
47
|
|
|
47
48
|
// Stringify
|
|
48
49
|
|
|
@@ -2,13 +2,15 @@ import {
|
|
|
2
2
|
QueryParamType,
|
|
3
3
|
QueryParamsType,
|
|
4
4
|
QueryParamValuesType,
|
|
5
|
-
|
|
5
|
+
ResponseReturnType,
|
|
6
6
|
QueryStringifyOptionsType,
|
|
7
|
+
AdapterInstance,
|
|
7
8
|
} from "adapter";
|
|
8
9
|
import { RequestInstance } from "request";
|
|
9
10
|
import { stringifyDefaultOptions } from "client";
|
|
10
11
|
import { NegativeTypes } from "types";
|
|
11
12
|
import { RequestInterceptorType, ResponseInterceptorType } from "./client.types";
|
|
13
|
+
import { hasWindow } from "managers";
|
|
12
14
|
|
|
13
15
|
// Utils
|
|
14
16
|
|
|
@@ -33,9 +35,9 @@ export const interceptRequest = async (interceptors: RequestInterceptorType[], r
|
|
|
33
35
|
return newRequest;
|
|
34
36
|
};
|
|
35
37
|
|
|
36
|
-
export const interceptResponse = async <GlobalErrorType>(
|
|
38
|
+
export const interceptResponse = async <GlobalErrorType, Adapter extends AdapterInstance>(
|
|
37
39
|
interceptors: ResponseInterceptorType[],
|
|
38
|
-
response:
|
|
40
|
+
response: ResponseReturnType<any, GlobalErrorType, Adapter>,
|
|
39
41
|
request: RequestInstance,
|
|
40
42
|
) => {
|
|
41
43
|
let newResponse = response;
|
|
@@ -52,7 +54,7 @@ export const interceptResponse = async <GlobalErrorType>(
|
|
|
52
54
|
// Mappers
|
|
53
55
|
|
|
54
56
|
export const getAdapterHeaders = (request: RequestInstance) => {
|
|
55
|
-
const isFormData = request.data instanceof FormData;
|
|
57
|
+
const isFormData = hasWindow() && request.data instanceof FormData;
|
|
56
58
|
const headers: HeadersInit = {};
|
|
57
59
|
|
|
58
60
|
if (!isFormData) headers["Content-Type"] = "application/json";
|
|
@@ -62,7 +64,7 @@ export const getAdapterHeaders = (request: RequestInstance) => {
|
|
|
62
64
|
};
|
|
63
65
|
|
|
64
66
|
export const getAdapterPayload = (data: unknown): string | FormData => {
|
|
65
|
-
const isFormData = data instanceof FormData;
|
|
67
|
+
const isFormData = hasWindow() && data instanceof FormData;
|
|
66
68
|
if (isFormData) return data;
|
|
67
69
|
|
|
68
70
|
return stringifyValue(data);
|
|
@@ -107,7 +109,19 @@ const encodeParams = (key: string, value: QueryParamType, options: QueryStringif
|
|
|
107
109
|
return "";
|
|
108
110
|
}
|
|
109
111
|
|
|
110
|
-
|
|
112
|
+
const parsedValue = () => {
|
|
113
|
+
if (value instanceof Date) {
|
|
114
|
+
return options.dateParser?.(value) || value.toISOString();
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
if (typeof value === "object" && !Array.isArray(value)) {
|
|
118
|
+
return options.objectParser?.(value) || JSON.stringify(value);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
return String(value);
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
return `${encodeValue(key, options)}=${encodeValue(parsedValue(), options)}`;
|
|
111
125
|
};
|
|
112
126
|
|
|
113
127
|
const encodeArray = (key: string, array: Array<QueryParamValuesType>, options: QueryStringifyOptionsType): string => {
|
|
@@ -3,19 +3,18 @@ import EventEmitter from "events";
|
|
|
3
3
|
import {
|
|
4
4
|
QueueDataType,
|
|
5
5
|
getRequestType,
|
|
6
|
-
isFailedRequest,
|
|
7
6
|
canRetryRequest,
|
|
8
7
|
getDispatcherEvents,
|
|
9
8
|
DispatcherRequestType,
|
|
10
9
|
DispatcherOptionsType,
|
|
11
10
|
DispatcherStorageType,
|
|
12
|
-
|
|
11
|
+
QueueElementType,
|
|
13
12
|
RunningRequestValueType,
|
|
14
13
|
} from "dispatcher";
|
|
15
14
|
import { ClientInstance } from "client";
|
|
16
15
|
import { getUniqueRequestId } from "utils";
|
|
17
16
|
import { ResponseDetailsType, LoggerType } from "managers";
|
|
18
|
-
import { RequestInstance
|
|
17
|
+
import { RequestInstance } from "request";
|
|
19
18
|
import { getErrorMessage } from "adapter";
|
|
20
19
|
|
|
21
20
|
/**
|
|
@@ -25,7 +24,7 @@ import { getErrorMessage } from "adapter";
|
|
|
25
24
|
export class Dispatcher {
|
|
26
25
|
public emitter = new EventEmitter();
|
|
27
26
|
public events = getDispatcherEvents(this.emitter);
|
|
28
|
-
public storage: DispatcherStorageType = new Map<string, QueueDataType<
|
|
27
|
+
public storage: DispatcherStorageType = new Map<string, QueueDataType<any>>();
|
|
29
28
|
|
|
30
29
|
private requestCount = new Map<string, number>();
|
|
31
30
|
private runningRequests = new Map<string, RunningRequestValueType[]>();
|
|
@@ -136,7 +135,7 @@ export class Dispatcher {
|
|
|
136
135
|
*/
|
|
137
136
|
addQueueElement = <Request extends RequestInstance = RequestInstance>(
|
|
138
137
|
queueKey: string,
|
|
139
|
-
dispatcherDump:
|
|
138
|
+
dispatcherDump: QueueElementType<Request>,
|
|
140
139
|
) => {
|
|
141
140
|
const queue = this.getQueue<Request>(queueKey);
|
|
142
141
|
queue.requests.push(dispatcherDump);
|
|
@@ -181,7 +180,7 @@ export class Dispatcher {
|
|
|
181
180
|
|
|
182
181
|
const isStopped = queue && queue.stopped;
|
|
183
182
|
const isOffline = !this.client.appManager.isOnline;
|
|
184
|
-
const isConcurrent = !queueElement?.
|
|
183
|
+
const isConcurrent = !queueElement?.request.queued;
|
|
185
184
|
const isInactive = !runningRequests.length;
|
|
186
185
|
const isEmpty = !queueElement;
|
|
187
186
|
|
|
@@ -379,10 +378,10 @@ export class Dispatcher {
|
|
|
379
378
|
// eslint-disable-next-line class-methods-use-this
|
|
380
379
|
createStorageElement = <Request extends RequestInstance>(request: Request) => {
|
|
381
380
|
const requestId = getUniqueRequestId(request.queueKey);
|
|
382
|
-
const storageElement:
|
|
381
|
+
const storageElement: QueueElementType<Request> = {
|
|
383
382
|
requestId,
|
|
384
383
|
timestamp: +new Date(),
|
|
385
|
-
|
|
384
|
+
request,
|
|
386
385
|
retries: 0,
|
|
387
386
|
stopped: false,
|
|
388
387
|
};
|
|
@@ -445,11 +444,10 @@ export class Dispatcher {
|
|
|
445
444
|
delete = (queueKey: string, requestId: string, abortKey: string) => {
|
|
446
445
|
this.logger.debug("Deleting request", { queueKey, requestId, abortKey });
|
|
447
446
|
const queue = this.getQueue(queueKey);
|
|
448
|
-
const
|
|
447
|
+
const queueElement = queue.requests.find((req) => req.requestId === requestId);
|
|
449
448
|
|
|
450
|
-
if (!
|
|
449
|
+
if (!queueElement) return;
|
|
451
450
|
|
|
452
|
-
const request = new Request(this.client, existingRequest.requestDump.requestOptions, existingRequest.requestDump);
|
|
453
451
|
queue.requests = queue.requests.filter((req) => req.requestId !== requestId);
|
|
454
452
|
this.storage.set(queueKey, queue);
|
|
455
453
|
|
|
@@ -462,7 +460,7 @@ export class Dispatcher {
|
|
|
462
460
|
// Emit Queue Changes
|
|
463
461
|
this.options?.onDeleteFromStorage?.(queueKey, queue);
|
|
464
462
|
this.events.setQueueChanged(queueKey, queue);
|
|
465
|
-
this.client.requestManager.events.emitRemove(queueKey, requestId, { requestId, request });
|
|
463
|
+
this.client.requestManager.events.emitRemove(queueKey, requestId, { requestId, request: queueElement.request });
|
|
466
464
|
|
|
467
465
|
if (!queue.requests.length) {
|
|
468
466
|
this.events.setDrained(queueKey, queue);
|
|
@@ -475,12 +473,11 @@ export class Dispatcher {
|
|
|
475
473
|
* Request can run for some time, once it's done, we have to check if it's successful or if it was aborted
|
|
476
474
|
* It can be different once the previous call was set as cancelled and removed from queue before this request got resolved
|
|
477
475
|
*/
|
|
478
|
-
performRequest = async (storageElement:
|
|
479
|
-
const request
|
|
480
|
-
const { requestDump, requestId } = storageElement;
|
|
476
|
+
performRequest = async (storageElement: QueueElementType) => {
|
|
477
|
+
const { request, requestId } = storageElement;
|
|
481
478
|
this.logger.info("Performing request", { request, requestId });
|
|
482
479
|
|
|
483
|
-
const { retry, retryTime, queueKey, cacheKey, abortKey, offline } =
|
|
480
|
+
const { retry, retryTime, queueKey, cacheKey, abortKey, offline } = request;
|
|
484
481
|
const { adapter, requestManager, cache, appManager } = this.client;
|
|
485
482
|
|
|
486
483
|
const canRetry = canRetryRequest(storageElement.retries, retry);
|
|
@@ -518,17 +515,14 @@ export class Dispatcher {
|
|
|
518
515
|
// Do not continue the request handling when it got stopped and request was unsuccessful
|
|
519
516
|
// Or when the request was aborted/canceled
|
|
520
517
|
const isOfflineResponseStatus = !appManager.isOnline;
|
|
521
|
-
// Request is failed when there is the error message or the status is 0 or equal/bigger than 400
|
|
522
|
-
const isFailed = isFailedRequest(response);
|
|
523
518
|
// If there is no running request with this id, it means it was cancelled and removed during send
|
|
524
|
-
const isCancelMessage = getErrorMessage("abort").message === response
|
|
519
|
+
const isCancelMessage = getErrorMessage("abort").message === response.error?.message;
|
|
525
520
|
const isCanceled = !this.hasRunningRequest(queueKey, requestId) || isCancelMessage;
|
|
526
521
|
|
|
527
522
|
// Remove running request, must be called after isCancelled
|
|
528
523
|
this.deleteRunningRequest(queueKey, requestId);
|
|
529
524
|
|
|
530
525
|
const requestDetails: ResponseDetailsType = {
|
|
531
|
-
isFailed,
|
|
532
526
|
isCanceled,
|
|
533
527
|
isOffline: isOfflineResponseStatus,
|
|
534
528
|
retries: storageElement.retries,
|
|
@@ -546,24 +540,24 @@ export class Dispatcher {
|
|
|
546
540
|
// Global response emitter to handle request execution
|
|
547
541
|
requestManager.events.emitResponse(cacheKey, requestId, response, requestDetails);
|
|
548
542
|
// Cache event to emit the data inside and store it
|
|
549
|
-
cache.set(request, response, requestDetails);
|
|
543
|
+
cache.set(request, { ...response, ...requestDetails });
|
|
550
544
|
this.logger.info("Request finished", { requestId, request, response, requestDetails });
|
|
551
545
|
|
|
552
546
|
// On cancelled
|
|
553
547
|
if (isCanceled) {
|
|
554
548
|
const queue = this.getQueue(queueKey);
|
|
555
|
-
const
|
|
549
|
+
const queueElement = queue.requests.find((req) => req.requestId === requestId);
|
|
556
550
|
|
|
557
551
|
// do not remove cancelled request as it may be result of manual queue pause
|
|
558
552
|
// if abort was done without stop action we can remove request
|
|
559
|
-
if (!queue.stopped && !
|
|
553
|
+
if (!queue.stopped && !queueElement?.stopped) {
|
|
560
554
|
this.logger.debug("Request paused", { response, requestDetails, request });
|
|
561
555
|
return this.delete(queueKey, requestId, abortKey);
|
|
562
556
|
}
|
|
563
557
|
return this.logger.debug("Request canceled", { response, requestDetails, request });
|
|
564
558
|
}
|
|
565
559
|
// On offline
|
|
566
|
-
if (
|
|
560
|
+
if (!response.success && isOfflineResponseStatus) {
|
|
567
561
|
// if we don't want to keep offline request - just delete them
|
|
568
562
|
if (!offline) {
|
|
569
563
|
this.logger.warning("Removing non-offline request", { response, requestDetails, request });
|
|
@@ -573,7 +567,7 @@ export class Dispatcher {
|
|
|
573
567
|
return this.logger.debug("Awaiting for network restoration", { response, requestDetails, request });
|
|
574
568
|
}
|
|
575
569
|
// On success
|
|
576
|
-
if (
|
|
570
|
+
if (response.success) {
|
|
577
571
|
this.delete(queueKey, requestId, abortKey);
|
|
578
572
|
return this.logger.debug("Successful response, removing request from queue.", {
|
|
579
573
|
response,
|
|
@@ -582,7 +576,7 @@ export class Dispatcher {
|
|
|
582
576
|
});
|
|
583
577
|
}
|
|
584
578
|
// On retry
|
|
585
|
-
if (
|
|
579
|
+
if (!response.success && canRetry) {
|
|
586
580
|
this.logger.debug("Waiting for retry", { response, requestDetails, request });
|
|
587
581
|
// Perform retry once request is failed
|
|
588
582
|
setTimeout(() => {
|