@hyper-fetch/core 6.0.1 → 7.0.1

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.
Files changed (83) hide show
  1. package/.eslintrc.json +8 -3
  2. package/README.md +5 -5
  3. package/dist/browser/index.js +3714 -0
  4. package/dist/browser/index.js.map +7 -0
  5. package/dist/index.d.ts +1669 -1091
  6. package/dist/index.js +3952 -0
  7. package/dist/index.js.map +7 -0
  8. package/package.json +16 -18
  9. package/src/adapter/adapter.bindings.ts +261 -165
  10. package/src/adapter/adapter.ts +480 -8
  11. package/src/adapter/adapter.types.ts +111 -139
  12. package/src/adapter/adapter.utils.ts +71 -25
  13. package/src/adapter/index.ts +1 -2
  14. package/src/cache/cache.events.ts +58 -14
  15. package/src/cache/cache.ts +158 -91
  16. package/src/cache/cache.types.ts +15 -25
  17. package/src/cache/cache.utils.ts +17 -10
  18. package/src/client/client.create.ts +17 -0
  19. package/src/client/client.ts +247 -266
  20. package/src/client/client.types.ts +43 -21
  21. package/src/client/client.utils.ts +7 -168
  22. package/src/client/index.ts +1 -0
  23. package/src/constants/http.constants.ts +6 -6
  24. package/src/constants/time.constants.ts +10 -10
  25. package/src/dispatcher/dispatcher.constants.ts +5 -5
  26. package/src/dispatcher/dispatcher.events.ts +85 -20
  27. package/src/dispatcher/dispatcher.ts +265 -199
  28. package/src/dispatcher/dispatcher.types.ts +6 -7
  29. package/src/dispatcher/dispatcher.utils.ts +26 -10
  30. package/src/http-adapter/http-adapter.browser.ts +101 -0
  31. package/src/http-adapter/http-adapter.constants.ts +8 -0
  32. package/src/http-adapter/http-adapter.server.ts +134 -0
  33. package/src/http-adapter/http-adapter.ts +11 -0
  34. package/src/http-adapter/http-adapter.types.ts +86 -0
  35. package/src/http-adapter/http-adapter.utils.ts +177 -0
  36. package/src/http-adapter/index.ts +4 -0
  37. package/src/index.ts +2 -1
  38. package/src/managers/app/app.manager.constants.ts +4 -4
  39. package/src/managers/app/app.manager.events.ts +12 -12
  40. package/src/managers/app/app.manager.ts +10 -7
  41. package/src/managers/app/app.manager.utils.ts +12 -2
  42. package/src/managers/logger/logger.manager.constants.ts +13 -18
  43. package/src/managers/logger/logger.manager.ts +37 -49
  44. package/src/managers/logger/logger.manager.types.ts +32 -21
  45. package/src/managers/logger/logger.manager.utils.ts +23 -17
  46. package/src/managers/request/request.manager.events.ts +222 -109
  47. package/src/managers/request/request.manager.ts +5 -2
  48. package/src/managers/request/request.manager.types.ts +35 -7
  49. package/src/managers/request/request.manager.utils.ts +29 -17
  50. package/src/mocker/mocker.ts +115 -81
  51. package/src/mocker/mocker.types.ts +29 -25
  52. package/src/plugin/index.ts +2 -0
  53. package/src/plugin/plugin.ts +159 -0
  54. package/src/plugin/plugin.types.ts +181 -0
  55. package/src/request/request.ts +366 -323
  56. package/src/request/request.types.ts +144 -148
  57. package/src/request/request.utils.ts +35 -32
  58. package/src/types/adapter.types.ts +63 -0
  59. package/src/types/client.types.ts +3 -3
  60. package/src/types/helpers.types.ts +16 -3
  61. package/src/types/hydration.types.ts +16 -0
  62. package/src/types/index.ts +3 -1
  63. package/src/types/request.types.ts +73 -0
  64. package/src/utils/emitter.utils.ts +52 -0
  65. package/src/utils/index.ts +1 -0
  66. package/src/utils/uuid.utils.ts +4 -2
  67. package/tsconfig.base.json +4 -5
  68. package/tsconfig.json +5 -4
  69. package/dist/browser/index.cjs.js +0 -2420
  70. package/dist/browser/index.cjs.js.map +0 -7
  71. package/dist/browser/index.esm.js +0 -2395
  72. package/dist/browser/index.esm.js.map +0 -7
  73. package/dist/index.cjs.js +0 -2579
  74. package/dist/index.cjs.js.map +0 -7
  75. package/dist/index.esm.js +0 -2474
  76. package/dist/index.esm.js.map +0 -7
  77. package/src/adapter/adapter.browser.ts +0 -100
  78. package/src/adapter/adapter.constants.ts +0 -8
  79. package/src/adapter/adapter.server.ts +0 -93
  80. package/src/effect/index.ts +0 -2
  81. package/src/effect/request.effect.ts +0 -31
  82. package/src/effect/request.effect.types.ts +0 -44
  83. package/src/types/fetch.types.ts +0 -50
@@ -1,3 +1,4 @@
1
+ /* eslint-disable max-lines */
1
2
  import {
2
3
  RequestSendOptionsType,
3
4
  ParamsType,
@@ -5,156 +6,180 @@ import {
5
6
  PayloadType,
6
7
  RequestJSON,
7
8
  RequestOptionsType,
8
- ExtractRouteParams,
9
9
  sendRequest,
10
- RequestCurrentType,
10
+ RequestConfigurationType,
11
11
  PayloadMapperType,
12
12
  RequestInstance,
13
13
  RequestMapper,
14
14
  ResponseMapper,
15
+ ExtractRouteParams,
15
16
  } from "request";
16
- import { Client } from "client";
17
- import { getUniqueRequestId } from "utils";
17
+ import { ClientInstance } from "client";
18
+ import { ResponseErrorType, ResponseSuccessType, ResponseType } from "adapter";
18
19
  import {
19
- AdapterType,
20
+ ExtractAdapterType,
21
+ ExtractClientAdapterType,
22
+ ExtractClientGlobalError,
23
+ ExtractEndpointType,
24
+ ExtractParamsType,
25
+ ExtractPayloadType,
26
+ ExtractQueryParamsType,
27
+ EmptyTypes,
20
28
  ExtractAdapterMethodType,
21
29
  ExtractAdapterOptionsType,
22
- QueryParamsType,
23
- AdapterInstance,
24
- } from "adapter";
25
- import { NegativeTypes } from "types";
26
- import { DateInterval } from "constants/time.constants";
27
- import { GeneratorReturnMockTypes, RequestDataMockTypes } from "mocker";
30
+ HydrateDataType,
31
+ SyncOrAsync,
32
+ } from "types";
33
+ import { Time } from "constants/time.constants";
34
+ import { MockerConfigType, MockResponseType } from "mocker";
28
35
 
29
36
  /**
30
- * Fetch request it is designed to prepare the necessary setup to execute the request to the server.
31
- * We can set up basic options for example endpoint, method, headers and advanced settings like cache, invalidation patterns, concurrency, retries and much, much more.
32
- * :::info Usage
33
- * We should not use this class directly in the standard development flow. We can initialize it using the `createRequest` method on the **Client** class.
34
- * :::
37
+ * Request is a class that represents a request sent to the server. It contains all the necessary information to make a request, like endpoint, method, headers, data, and much more.
38
+ * It is executed at any time via methods like `send` or `exec`.
39
+ *
40
+ * We can set it up with options like endpoint, method, headers and more.
41
+ * We can choose some of advanced settings like cache, invalidation patterns, concurrency, retries and much, much more.
35
42
  *
36
- * @attention
37
- * The most important thing about the request is that it keeps data in the format that can be dumped. This is necessary for the persistence and different dispatcher storage types.
43
+ * @info We should not use this class directly in the standard development flow.
44
+ * We can initialize it using the `createRequest` method on the **Client** class.
45
+ *
46
+ * @attention The most important thing about the request is that it keeps data in the format that can be dumped.
47
+ * This is necessary for the persistence and different dispatcher storage types.
38
48
  * This class doesn't have any callback methods by design and communicate with dispatcher and cache by events.
49
+ *
50
+ * It should be serializable to JSON and deserializable back to the class.
51
+ * Serialization should not affect the result of the request, so it's methods and functional part should be only syntax sugar for given runtime.
39
52
  */
53
+
40
54
  export class Request<
41
55
  Response,
42
56
  Payload,
43
57
  QueryParams,
44
- GlobalError, // Global Error Type
45
- LocalError, // Additional Error for specific endpoint
58
+ LocalError,
46
59
  Endpoint extends string,
47
- Adapter extends AdapterInstance = AdapterType,
48
- HasData extends true | false = false,
60
+ Client extends ClientInstance,
61
+ HasPayload extends true | false = false,
49
62
  HasParams extends true | false = false,
50
63
  HasQuery extends true | false = false,
51
64
  > {
52
65
  endpoint: Endpoint;
53
66
  headers?: HeadersInit;
54
67
  auth: boolean;
55
- method: ExtractAdapterMethodType<Adapter>;
56
- params: ExtractRouteParams<Endpoint> | NegativeTypes;
57
- data: PayloadType<Payload>;
58
- queryParams: QueryParams | NegativeTypes;
59
- options?: ExtractAdapterOptionsType<Adapter> | undefined;
68
+ method: ExtractAdapterMethodType<ExtractClientAdapterType<Client>>;
69
+ params: ExtractRouteParams<Endpoint> | EmptyTypes;
70
+ payload: PayloadType<Payload>;
71
+ queryParams: QueryParams | EmptyTypes;
72
+ options?: ExtractAdapterOptionsType<ExtractClientAdapterType<Client>> | undefined;
60
73
  cancelable: boolean;
61
74
  retry: number;
62
75
  retryTime: number;
63
- garbageCollection: number;
64
- cache: boolean;
65
76
  cacheTime: number;
77
+ cache: boolean;
78
+ staleTime: number;
66
79
  queued: boolean;
67
80
  offline: boolean;
68
81
  abortKey: string;
69
82
  cacheKey: string;
70
- queueKey: string;
71
- effectKey: string;
83
+ queryKey: string;
72
84
  used: boolean;
73
85
  deduplicate: boolean;
74
- deduplicateTime: number;
75
- dataMapper?: PayloadMapperType<Payload>;
76
- mock?: Generator<
77
- GeneratorReturnMockTypes<Response, this>,
78
- GeneratorReturnMockTypes<Response, this>,
79
- GeneratorReturnMockTypes<Response, this>
80
- >;
81
- mockData?: RequestDataMockTypes<Response, this>;
82
- isMockEnabled = false;
83
- requestMapper?: RequestMapper<this, any>;
84
- responseMapper?: ResponseMapper<this, any, any>;
86
+ deduplicateTime: number | null;
87
+
88
+ isMockerEnabled = false;
89
+
90
+ unstable_mock?: {
91
+ fn: (options: {
92
+ request: RequestInstance;
93
+ requestId: string;
94
+ }) => MockResponseType<Response, LocalError | ExtractClientGlobalError<Client>, ExtractClientAdapterType<Client>>;
95
+ config: MockerConfigType;
96
+ };
97
+ /** @internal */
98
+ unstable_payloadMapper?: PayloadMapperType<Payload>;
99
+ /** @internal */
100
+ unstable_requestMapper?: RequestMapper<any, any>;
101
+ /** @internal */
102
+ unstable_responseMapper?: ResponseMapper<this, ResponseSuccessType<any, any> | ResponseErrorType<any, any>>;
85
103
 
86
104
  private updatedAbortKey: boolean;
87
105
  private updatedCacheKey: boolean;
88
- private updatedQueueKey: boolean;
89
- private updatedEffectKey: boolean;
106
+ private updatedQueryKey: boolean;
90
107
 
91
108
  constructor(
92
- readonly client: Client<GlobalError, Adapter>,
109
+ readonly client: Client,
93
110
  readonly requestOptions: RequestOptionsType<
94
111
  Endpoint,
95
- ExtractAdapterOptionsType<Adapter>,
96
- ExtractAdapterMethodType<Adapter>
112
+ ExtractAdapterOptionsType<ExtractClientAdapterType<Client>>,
113
+ ExtractAdapterMethodType<ExtractClientAdapterType<Client>>
97
114
  >,
98
- readonly requestJSON?:
99
- | RequestCurrentType<
115
+ readonly initialRequestConfiguration?:
116
+ | RequestConfigurationType<
100
117
  Payload,
118
+ Endpoint extends string ? ExtractRouteParams<Endpoint> : never,
101
119
  QueryParams,
102
120
  Endpoint,
103
- ExtractAdapterOptionsType<Adapter>,
104
- ExtractAdapterMethodType<Adapter>
121
+ ExtractAdapterOptionsType<ExtractClientAdapterType<Client>>,
122
+ ExtractAdapterMethodType<ExtractClientAdapterType<Client>>
105
123
  >
106
124
  | undefined,
107
125
  ) {
126
+ const configuration: RequestOptionsType<
127
+ Endpoint,
128
+ ExtractAdapterOptionsType<ExtractClientAdapterType<Client>>,
129
+ ExtractAdapterMethodType<ExtractClientAdapterType<Client>>
130
+ > = {
131
+ ...(this.client.adapter.unstable_getRequestDefaults?.(requestOptions) as RequestOptionsType<
132
+ Endpoint,
133
+ ExtractAdapterOptionsType<ExtractClientAdapterType<Client>>,
134
+ ExtractAdapterMethodType<ExtractClientAdapterType<Client>>
135
+ >),
136
+ ...requestOptions,
137
+ };
108
138
  const {
109
139
  endpoint,
110
140
  headers,
111
141
  auth = true,
112
- method = client.defaultMethod,
142
+ method = client.adapter.defaultMethod,
113
143
  options,
114
144
  cancelable = false,
115
145
  retry = 0,
116
146
  retryTime = 500,
117
- garbageCollection = DateInterval.minute * 5,
147
+ cacheTime = Time.MIN * 5,
118
148
  cache = true,
119
- cacheTime = DateInterval.minute * 5,
149
+ staleTime = Time.MIN * 5,
120
150
  queued = false,
121
151
  offline = true,
122
152
  abortKey,
123
153
  cacheKey,
124
- queueKey,
125
- effectKey,
154
+ queryKey,
126
155
  deduplicate = false,
127
- deduplicateTime = 10,
128
- } = { ...this.client.requestDefaultOptions?.(requestOptions), ...requestOptions };
129
-
130
- this.endpoint = requestJSON?.endpoint ?? endpoint;
131
- this.headers = requestJSON?.headers ?? headers;
132
- this.auth = requestJSON?.auth ?? auth;
133
- this.method = method;
134
- this.params = requestJSON?.params;
135
- this.data = requestJSON?.data;
136
- this.queryParams = requestJSON?.queryParams;
137
- this.options = requestJSON?.options ?? options;
138
- this.cancelable = requestJSON?.cancelable ?? cancelable;
139
- this.retry = requestJSON?.retry ?? retry;
140
- this.retryTime = requestJSON?.retryTime ?? retryTime;
141
- this.garbageCollection = requestJSON?.garbageCollection ?? garbageCollection;
142
- this.cache = requestJSON?.cache ?? cache;
143
- this.cacheTime = requestJSON?.cacheTime ?? cacheTime;
144
- this.queued = requestJSON?.queued ?? queued;
145
- this.offline = requestJSON?.offline ?? offline;
146
- this.abortKey = requestJSON?.abortKey ?? abortKey ?? this.client.abortKeyMapper(this);
147
- this.cacheKey = requestJSON?.cacheKey ?? cacheKey ?? this.client.cacheKeyMapper(this);
148
- this.queueKey = requestJSON?.queueKey ?? queueKey ?? this.client.queueKeyMapper(this);
149
- this.effectKey = requestJSON?.effectKey ?? effectKey ?? this.client.effectKeyMapper(this);
150
- this.used = requestJSON?.used ?? false;
151
- this.deduplicate = requestJSON?.deduplicate ?? deduplicate;
152
- this.deduplicateTime = requestJSON?.deduplicateTime ?? deduplicateTime;
153
-
154
- this.updatedAbortKey = requestJSON?.updatedAbortKey ?? false;
155
- this.updatedCacheKey = requestJSON?.updatedCacheKey ?? false;
156
- this.updatedQueueKey = requestJSON?.updatedQueueKey ?? false;
157
- this.updatedEffectKey = requestJSON?.updatedEffectKey ?? false;
156
+ deduplicateTime = null,
157
+ } = configuration;
158
+ this.endpoint = initialRequestConfiguration?.endpoint ?? endpoint;
159
+ this.headers = initialRequestConfiguration?.headers ?? headers;
160
+ this.auth = initialRequestConfiguration?.auth ?? auth;
161
+ this.method = method as ExtractAdapterMethodType<ExtractClientAdapterType<Client>>;
162
+ this.params = initialRequestConfiguration?.params;
163
+ this.payload = initialRequestConfiguration?.payload;
164
+ this.queryParams = initialRequestConfiguration?.queryParams;
165
+ this.options = initialRequestConfiguration?.options ?? options;
166
+ this.cancelable = initialRequestConfiguration?.cancelable ?? cancelable;
167
+ this.retry = initialRequestConfiguration?.retry ?? retry;
168
+ this.retryTime = initialRequestConfiguration?.retryTime ?? retryTime;
169
+ this.cacheTime = initialRequestConfiguration?.cacheTime ?? cacheTime;
170
+ this.cache = initialRequestConfiguration?.cache ?? cache;
171
+ this.staleTime = initialRequestConfiguration?.staleTime ?? staleTime;
172
+ this.queued = initialRequestConfiguration?.queued ?? queued;
173
+ this.offline = initialRequestConfiguration?.offline ?? offline;
174
+ this.abortKey = initialRequestConfiguration?.abortKey ?? abortKey ?? this.client.unstable_abortKeyMapper(this);
175
+ this.cacheKey = initialRequestConfiguration?.cacheKey ?? cacheKey ?? this.client.unstable_cacheKeyMapper(this);
176
+ this.queryKey = initialRequestConfiguration?.queryKey ?? queryKey ?? this.client.unstable_queryKeyMapper(this);
177
+ this.used = initialRequestConfiguration?.used ?? false;
178
+ this.deduplicate = initialRequestConfiguration?.deduplicate ?? deduplicate;
179
+ this.deduplicateTime = initialRequestConfiguration?.deduplicateTime ?? deduplicateTime;
180
+ this.updatedAbortKey = initialRequestConfiguration?.updatedAbortKey ?? false;
181
+ this.updatedCacheKey = initialRequestConfiguration?.updatedCacheKey ?? false;
182
+ this.updatedQueryKey = initialRequestConfiguration?.updatedQueryKey ?? false;
158
183
  }
159
184
 
160
185
  public setHeaders = (headers: HeadersInit) => {
@@ -165,22 +190,22 @@ export class Request<
165
190
  return this.clone({ auth });
166
191
  };
167
192
 
168
- public setParams = <P extends ExtractRouteParams<Endpoint>>(params: P) => {
169
- return this.clone<HasData, P extends null ? false : true, HasQuery>({ params });
193
+ public setParams = <P extends ExtractParamsType<this>>(params: P) => {
194
+ return this.clone<HasPayload, P extends null ? false : true, HasQuery>({ params });
170
195
  };
171
196
 
172
- public setData = <D extends Payload>(data: D) => {
173
- return this.clone<D extends null ? false : true, HasParams, HasQuery>({
174
- data,
197
+ public setPayload = <P extends Payload>(payload: P) => {
198
+ return this.clone<P extends null ? false : true, HasParams, HasQuery>({
199
+ payload,
175
200
  });
176
201
  };
177
202
 
178
203
  public setQueryParams = (queryParams: QueryParams) => {
179
- return this.clone<HasData, HasParams, true>({ queryParams });
204
+ return this.clone<HasPayload, HasParams, true>({ queryParams });
180
205
  };
181
206
 
182
- public setOptions = (options: ExtractAdapterOptionsType<Adapter>) => {
183
- return this.clone<HasData, HasParams, true>({ options });
207
+ public setOptions = (options: ExtractAdapterOptionsType<ExtractClientAdapterType<Client>>) => {
208
+ return this.clone<HasPayload, HasParams, true>({ options });
184
209
  };
185
210
 
186
211
  public setCancelable = (cancelable: boolean) => {
@@ -188,7 +213,11 @@ export class Request<
188
213
  };
189
214
 
190
215
  public setRetry = (
191
- retry: RequestOptionsType<Endpoint, ExtractAdapterOptionsType<Adapter>, ExtractAdapterMethodType<Adapter>>["retry"],
216
+ retry: RequestOptionsType<
217
+ Endpoint,
218
+ ExtractAdapterOptionsType<ExtractClientAdapterType<Client>>,
219
+ ExtractAdapterMethodType<ExtractClientAdapterType<Client>>
220
+ >["retry"],
192
221
  ) => {
193
222
  return this.clone({ retry });
194
223
  };
@@ -196,37 +225,41 @@ export class Request<
196
225
  public setRetryTime = (
197
226
  retryTime: RequestOptionsType<
198
227
  Endpoint,
199
- ExtractAdapterOptionsType<Adapter>,
200
- ExtractAdapterMethodType<Adapter>
228
+ ExtractAdapterOptionsType<ExtractClientAdapterType<Client>>,
229
+ ExtractAdapterMethodType<ExtractClientAdapterType<Client>>
201
230
  >["retryTime"],
202
231
  ) => {
203
232
  return this.clone({ retryTime });
204
233
  };
205
234
 
206
- public setGarbageCollection = (
207
- garbageCollection: RequestOptionsType<
235
+ public setCacheTime = (
236
+ cacheTime: RequestOptionsType<
208
237
  Endpoint,
209
- ExtractAdapterOptionsType<Adapter>,
210
- ExtractAdapterMethodType<Adapter>
211
- >["garbageCollection"],
238
+ ExtractAdapterOptionsType<ExtractClientAdapterType<Client>>,
239
+ ExtractAdapterMethodType<ExtractClientAdapterType<Client>>
240
+ >["cacheTime"],
212
241
  ) => {
213
- return this.clone({ garbageCollection });
242
+ return this.clone({ cacheTime });
214
243
  };
215
244
 
216
245
  public setCache = (
217
- cache: RequestOptionsType<Endpoint, ExtractAdapterOptionsType<Adapter>, ExtractAdapterMethodType<Adapter>>["cache"],
246
+ cache: RequestOptionsType<
247
+ Endpoint,
248
+ ExtractAdapterOptionsType<ExtractClientAdapterType<Client>>,
249
+ ExtractAdapterMethodType<ExtractClientAdapterType<Client>>
250
+ >["cache"],
218
251
  ) => {
219
252
  return this.clone({ cache });
220
253
  };
221
254
 
222
- public setCacheTime = (
223
- cacheTime: RequestOptionsType<
255
+ public setStaleTime = (
256
+ staleTime: RequestOptionsType<
224
257
  Endpoint,
225
- ExtractAdapterOptionsType<Adapter>,
226
- ExtractAdapterMethodType<Adapter>
227
- >["cacheTime"],
258
+ ExtractAdapterOptionsType<ExtractClientAdapterType<Client>>,
259
+ ExtractAdapterMethodType<ExtractClientAdapterType<Client>>
260
+ >["staleTime"],
228
261
  ) => {
229
- return this.clone({ cacheTime });
262
+ return this.clone({ staleTime });
230
263
  };
231
264
 
232
265
  public setQueued = (queued: boolean) => {
@@ -243,14 +276,9 @@ export class Request<
243
276
  return this.clone({ cacheKey });
244
277
  };
245
278
 
246
- public setQueueKey = (queueKey: string) => {
247
- this.updatedQueueKey = true;
248
- return this.clone({ queueKey });
249
- };
250
-
251
- public setEffectKey = (effectKey: string) => {
252
- this.updatedEffectKey = true;
253
- return this.clone({ effectKey });
279
+ public setQueryKey = (queryKey: string) => {
280
+ this.updatedQueryKey = true;
281
+ return this.clone({ queryKey });
254
282
  };
255
283
 
256
284
  public setDeduplicate = (deduplicate: boolean) => {
@@ -269,52 +297,42 @@ export class Request<
269
297
  return this.clone({ offline });
270
298
  };
271
299
 
272
- public setMock = (mockData: RequestDataMockTypes<Response, this>) => {
273
- const mockGenerator = function* mocked(mockedValues: RequestDataMockTypes<Response, RequestInstance>) {
274
- if (Array.isArray(mockData)) {
275
- let iteration = 0;
276
- // eslint-disable-next-line no-restricted-syntax
277
- while (true) {
278
- yield mockedValues[iteration];
279
- iteration = mockData.length === iteration + 1 ? 0 : iteration + 1;
280
- }
281
- } else {
282
- while (true) {
283
- yield mockData;
284
- }
285
- }
286
- };
287
- this.mockData = mockData;
288
- this.mock = mockGenerator(mockData);
289
- this.isMockEnabled = true;
300
+ public setMock = (
301
+ fn: (options: {
302
+ request: Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, HasPayload, HasParams, HasQuery>;
303
+ requestId: string;
304
+ }) => SyncOrAsync<
305
+ MockResponseType<Response, LocalError | ExtractClientGlobalError<Client>, ExtractClientAdapterType<Client>>
306
+ >,
307
+ config: MockerConfigType = {},
308
+ ) => {
309
+ this.unstable_mock = { fn, config } as typeof this.unstable_mock;
310
+ this.isMockerEnabled = true;
290
311
  return this;
291
312
  };
292
313
 
293
- public removeMock = () => {
294
- this.mockData = null;
295
- this.mock = null;
296
- this.isMockEnabled = false;
314
+ public clearMock = () => {
315
+ this.unstable_mock = undefined;
316
+ this.isMockerEnabled = false;
297
317
  return this;
298
318
  };
299
319
 
300
- public setEnableMocking = (isMockEnabled: boolean) => {
301
- this.isMockEnabled = isMockEnabled;
320
+ public setMockingEnabled = (isMockerEnabled: boolean) => {
321
+ this.isMockerEnabled = isMockerEnabled;
302
322
  return this;
303
323
  };
304
324
 
305
- /**
306
- * Mappers
307
- */
308
-
309
325
  /**
310
326
  * Map data before it gets send to the server
311
- * @param dataMapper
327
+ * @param payloadMapper
312
328
  * @returns
313
329
  */
314
- public setDataMapper = <DataMapper extends (data: Payload) => any | Promise<any>>(dataMapper: DataMapper) => {
315
- const cloned = this.clone<HasData, HasParams, HasQuery>(undefined);
330
+ public setPayloadMapper = <MappedPayload extends any | Promise<any>>(
331
+ payloadMapper: (data: Payload) => MappedPayload,
332
+ ) => {
333
+ const cloned = this.clone<HasPayload, HasParams, HasQuery>(undefined);
316
334
 
317
- cloned.dataMapper = dataMapper;
335
+ cloned.unstable_payloadMapper = payloadMapper as typeof this.unstable_payloadMapper;
318
336
 
319
337
  return cloned;
320
338
  };
@@ -325,9 +343,9 @@ export class Request<
325
343
  * @returns new request
326
344
  */
327
345
  public setRequestMapper = <NewRequest extends RequestInstance>(requestMapper: RequestMapper<this, NewRequest>) => {
328
- const cloned = this.clone<HasData, HasParams, HasQuery>(undefined);
346
+ const cloned = this.clone<HasPayload, HasParams, HasQuery>(undefined);
329
347
 
330
- cloned.requestMapper = requestMapper;
348
+ cloned.unstable_requestMapper = requestMapper;
331
349
 
332
350
  return cloned;
333
351
  };
@@ -337,117 +355,135 @@ export class Request<
337
355
  * @param responseMapper our mapping callback
338
356
  * @returns new response
339
357
  */
340
- public setResponseMapper = <NewResponse = Response, NewError = GlobalError | LocalError>(
341
- responseMapper?: ResponseMapper<this, NewResponse, NewError>,
358
+ public setResponseMapper = <MappedResponse extends ResponseSuccessType<any, any> | ResponseErrorType<any, any>>(
359
+ responseMapper?: ResponseMapper<this, MappedResponse>,
342
360
  ) => {
343
- const cloned = this.clone<HasData, HasParams, HasQuery>();
361
+ const cloned = this.clone<HasPayload, HasParams, HasQuery>();
344
362
 
345
- cloned.responseMapper = responseMapper;
363
+ cloned.unstable_responseMapper = responseMapper;
346
364
 
347
365
  return cloned as unknown as Request<
348
- NewResponse,
366
+ MappedResponse extends ResponseType<infer R, any, any> ? R : Response,
349
367
  Payload,
350
368
  QueryParams,
351
- GlobalError,
352
- LocalError,
369
+ MappedResponse extends ResponseType<any, infer E, any> ? E : LocalError,
353
370
  Endpoint,
354
- Adapter,
355
- HasData,
371
+ Client,
372
+ HasPayload,
356
373
  HasParams,
357
374
  HasQuery
358
375
  >;
359
376
  };
360
377
 
361
- private paramsMapper = (params: ParamsType | null | undefined, queryParams: QueryParams | NegativeTypes): string => {
362
- let endpoint = this.requestOptions.endpoint as string;
378
+ private paramsMapper = (params: ParamsType | null | undefined): Endpoint => {
379
+ const { endpoint } = this.requestOptions;
380
+
381
+ let stringEndpoint = String(endpoint);
363
382
  if (params) {
364
383
  Object.entries(params).forEach(([key, value]) => {
365
- endpoint = endpoint.replace(new RegExp(`:${key}`, "g"), String(value));
384
+ stringEndpoint = endpoint.replace(new RegExp(`:${key}`, "g"), String(value));
366
385
  });
367
386
  }
368
- if (queryParams) {
369
- endpoint += this.client.stringifyQueryParams(queryParams as unknown as QueryParamsType);
370
- }
371
- return endpoint;
387
+
388
+ return stringEndpoint as Endpoint;
372
389
  };
373
390
 
374
- public toJSON(): RequestJSON<this, ExtractAdapterOptionsType<Adapter>, QueryParams> {
391
+ public toJSON(): RequestJSON<this> {
375
392
  return {
376
- requestOptions: this.requestOptions,
377
- endpoint: this.endpoint,
393
+ requestOptions: this.requestOptions as unknown as RequestOptionsType<
394
+ ExtractEndpointType<this>,
395
+ ExtractAdapterOptionsType<ExtractAdapterType<this>>,
396
+ ExtractAdapterMethodType<ExtractAdapterType<this>>
397
+ >,
398
+ endpoint: this.endpoint as ExtractEndpointType<this>,
378
399
  headers: this.headers,
379
400
  auth: this.auth,
380
- method: this.method,
381
- params: this.params as any,
382
- data: this.data as any,
383
- queryParams: this.queryParams,
401
+ // TODO: fix this type
402
+ method: this.method as any,
403
+ params: this.params as ExtractParamsType<this>,
404
+ payload: this.payload as ExtractPayloadType<this>,
405
+ queryParams: this.queryParams as ExtractQueryParamsType<this>,
384
406
  options: this.options,
385
407
  cancelable: this.cancelable,
386
408
  retry: this.retry,
387
409
  retryTime: this.retryTime,
388
- garbageCollection: this.garbageCollection,
389
- cache: this.cache,
390
410
  cacheTime: this.cacheTime,
411
+ cache: this.cache,
412
+ staleTime: this.staleTime,
391
413
  queued: this.queued,
392
414
  offline: this.offline,
393
415
  abortKey: this.abortKey,
394
416
  cacheKey: this.cacheKey,
395
- queueKey: this.queueKey,
396
- effectKey: this.effectKey,
417
+ queryKey: this.queryKey,
397
418
  used: this.used,
398
419
  disableResponseInterceptors: this.requestOptions.disableResponseInterceptors,
399
420
  disableRequestInterceptors: this.requestOptions.disableRequestInterceptors,
400
421
  updatedAbortKey: this.updatedAbortKey,
401
422
  updatedCacheKey: this.updatedCacheKey,
402
- updatedQueueKey: this.updatedQueueKey,
403
- updatedEffectKey: this.updatedEffectKey,
423
+ updatedQueryKey: this.updatedQueryKey,
404
424
  deduplicate: this.deduplicate,
405
425
  deduplicateTime: this.deduplicateTime,
426
+ isMockerEnabled: this.isMockerEnabled,
427
+ hasMock: !!this.unstable_mock,
406
428
  };
407
429
  }
408
430
 
409
- public clone<D extends true | false = HasData, P extends true | false = HasParams, Q extends true | false = HasQuery>(
410
- options?: RequestCurrentType<
431
+ public clone<
432
+ NewData extends true | false = HasPayload,
433
+ NewParams extends true | false = HasParams,
434
+ NewQueryParams extends true | false = HasQuery,
435
+ >(
436
+ configuration?: RequestConfigurationType<
411
437
  Payload,
438
+ (typeof this)["params"],
412
439
  QueryParams,
413
440
  Endpoint,
414
- ExtractAdapterOptionsType<Adapter>,
415
- ExtractAdapterMethodType<Adapter>
441
+ ExtractAdapterOptionsType<ExtractClientAdapterType<Client>>,
442
+ ExtractAdapterMethodType<ExtractClientAdapterType<Client>>
416
443
  >,
417
- ): Request<Response, Payload, QueryParams, GlobalError, LocalError, Endpoint, Adapter, D, P, Q> {
444
+ ) {
418
445
  const json = this.toJSON();
419
- const requestJSON: RequestCurrentType<
446
+ const initialRequestConfiguration: RequestConfigurationType<
420
447
  Payload,
448
+ Endpoint extends string ? ExtractRouteParams<Endpoint> : never,
421
449
  QueryParams,
422
450
  Endpoint,
423
- ExtractAdapterOptionsType<Adapter>,
424
- ExtractAdapterMethodType<Adapter>
451
+ ExtractAdapterOptionsType<ExtractClientAdapterType<Client>>,
452
+ ExtractAdapterMethodType<ExtractClientAdapterType<Client>>
425
453
  > = {
426
454
  ...json,
427
- ...options,
428
- abortKey: this.updatedAbortKey ? options?.abortKey || this.abortKey : undefined,
429
- cacheKey: this.updatedCacheKey ? options?.cacheKey || this.cacheKey : undefined,
430
- queueKey: this.updatedQueueKey ? options?.queueKey || this.queueKey : undefined,
431
- endpoint: this.paramsMapper(options?.params || this.params, options?.queryParams || this.queryParams) as Endpoint,
432
- queryParams: options?.queryParams || this.queryParams,
433
- // Typescript circular types issue - we have to leave any here
434
- data: (options?.data || this.data) as any,
455
+ ...configuration,
456
+ options: configuration?.options || this.options,
457
+ abortKey: this.updatedAbortKey ? configuration?.abortKey || this.abortKey : undefined,
458
+ cacheKey: this.updatedCacheKey ? configuration?.cacheKey || this.cacheKey : undefined,
459
+ queryKey: this.updatedQueryKey ? configuration?.queryKey || this.queryKey : undefined,
460
+ endpoint: this.paramsMapper(configuration?.params || this.params),
461
+ queryParams: configuration?.queryParams || this.queryParams,
462
+ payload: configuration?.payload || this.payload,
463
+ params: (configuration?.params || this.params) as
464
+ | EmptyTypes
465
+ | (Endpoint extends string ? ExtractRouteParams<Endpoint> : never),
435
466
  };
436
467
 
437
- const cloned = new Request<Response, Payload, QueryParams, GlobalError, LocalError, Endpoint, Adapter, D, P, Q>(
438
- this.client,
439
- this.requestOptions,
440
- requestJSON,
441
- );
468
+ const cloned = new Request<
469
+ Response,
470
+ Payload,
471
+ QueryParams,
472
+ LocalError,
473
+ Endpoint,
474
+ Client,
475
+ NewData,
476
+ NewParams,
477
+ NewQueryParams
478
+ >(this.client, this.requestOptions, initialRequestConfiguration);
442
479
 
443
480
  // Inherit methods
444
- cloned.dataMapper = this.dataMapper;
445
- cloned.responseMapper = this.responseMapper;
446
- cloned.requestMapper = this.requestMapper;
481
+ cloned.unstable_payloadMapper = this.unstable_payloadMapper;
482
+ cloned.unstable_responseMapper = this.unstable_responseMapper;
483
+ cloned.unstable_requestMapper = this.unstable_requestMapper;
447
484
 
448
- cloned.mockData = this.mockData;
449
- cloned.mock = this.mock;
450
- cloned.isMockEnabled = this.isMockEnabled;
485
+ cloned.unstable_mock = this.unstable_mock;
486
+ cloned.isMockerEnabled = this.isMockerEnabled;
451
487
 
452
488
  return cloned;
453
489
  }
@@ -459,6 +495,80 @@ export class Request<
459
495
  return this.clone();
460
496
  };
461
497
 
498
+ public dehydrate = (config?: {
499
+ /** in case of using adapter without cache we can provide response to dehydrate */
500
+ response?: ResponseType<Response, LocalError | ExtractClientGlobalError<Client>, ExtractClientAdapterType<Client>>;
501
+ /** override cache data */
502
+ override?: boolean;
503
+ }):
504
+ | HydrateDataType<Response, LocalError | ExtractClientGlobalError<Client>, ExtractClientAdapterType<Client>>
505
+ | undefined => {
506
+ const { response, override = true } = config || {};
507
+
508
+ if (response) {
509
+ return {
510
+ override,
511
+ cacheTime: this.cacheTime,
512
+ staleTime: this.staleTime,
513
+ cacheKey: this.cacheKey,
514
+ timestamp: +new Date(),
515
+ hydrated: true,
516
+ cache: true,
517
+ response,
518
+ };
519
+ }
520
+
521
+ const cacheData = this.client.cache.get<Response, LocalError | ExtractClientGlobalError<Client>>(this.cacheKey);
522
+
523
+ if (!cacheData) {
524
+ return undefined;
525
+ }
526
+
527
+ return {
528
+ override,
529
+ cacheTime: this.cacheTime,
530
+ staleTime: this.staleTime,
531
+ cacheKey: this.cacheKey,
532
+ timestamp: +new Date(),
533
+ hydrated: true,
534
+ cache: true,
535
+ response: {
536
+ data: cacheData.data,
537
+ error: cacheData.error,
538
+ status: cacheData.status,
539
+ success: cacheData.success,
540
+ extra: cacheData.extra,
541
+ requestTimestamp: cacheData.requestTimestamp,
542
+ responseTimestamp: cacheData.responseTimestamp,
543
+ },
544
+ };
545
+ };
546
+
547
+ /**
548
+ * Read the response from cache data
549
+ *
550
+ * If it returns error and data at the same time, it means that latest request was failed
551
+ * and we show previous data from cache together with error received from actual request
552
+ */
553
+ public read():
554
+ | ResponseType<Response, LocalError | ExtractClientGlobalError<Client>, ExtractClientAdapterType<Client>>
555
+ | undefined {
556
+ const cacheData = this.client.cache.get<Response, LocalError | ExtractClientGlobalError<Client>>(this.cacheKey);
557
+
558
+ if (cacheData) {
559
+ return {
560
+ data: cacheData.data,
561
+ error: cacheData.error,
562
+ status: cacheData.status,
563
+ success: cacheData.success,
564
+ extra: cacheData.extra,
565
+ requestTimestamp: cacheData.requestTimestamp,
566
+ responseTimestamp: cacheData.responseTimestamp,
567
+ };
568
+ }
569
+ return undefined;
570
+ }
571
+
462
572
  /**
463
573
  * Method to use the request WITHOUT adding it to cache and queues. This mean it will make simple request without queue side effects.
464
574
  * @param options
@@ -470,20 +580,20 @@ export class Request<
470
580
  */
471
581
  public exec: RequestSendType<this> = async (options?: RequestSendOptionsType<this>) => {
472
582
  const { adapter, requestManager } = this.client;
473
- const request = this.clone(options as any) as this;
583
+ const request = this.clone(options);
474
584
 
475
- const requestId = getUniqueRequestId(this.queueKey);
585
+ const requestId = this.client.unstable_requestIdMapper(this);
476
586
 
477
587
  // Listen for aborting
478
588
  requestManager.addAbortController(this.abortKey, requestId);
479
589
 
480
- const response = await adapter(request, requestId);
590
+ const response = await adapter.fetch(request, requestId);
481
591
 
482
592
  // Stop listening for aborting
483
593
  requestManager.removeAbortController(this.abortKey, requestId);
484
594
 
485
- if (request.responseMapper) {
486
- return request.responseMapper(response);
595
+ if (request.unstable_responseMapper) {
596
+ return request.unstable_responseMapper(response);
487
597
  }
488
598
 
489
599
  return response;
@@ -500,115 +610,48 @@ export class Request<
500
610
  * ```
501
611
  */
502
612
  public send: RequestSendType<this> = async (options?: RequestSendOptionsType<this>) => {
503
- const { dispatcherType, ...rest } = options || {};
613
+ const { dispatcherType, ...configuration } = options || {};
504
614
 
505
- const request = this.clone(rest as any) as any;
506
- return sendRequest<this>(request, options);
615
+ const request = this.clone(configuration);
616
+ return sendRequest(request as unknown as this, options);
507
617
  };
508
- }
509
618
 
510
- // /**
511
- // * Typescript test cases
512
- // */
513
- //
514
- // const client = new Client({
515
- // url: "http://localhost:3000",
516
- // });
517
- //
518
- // const getUsers = client.createRequest<{ id: string }[]>()({
519
- // method: "GET",
520
- // endpoint: "/users",
521
- // });
522
- //
523
- // const getUser = client.createRequest<{ id: string }>()({
524
- // method: "GET",
525
- // endpoint: "/users/:id",
526
- // });
527
- //
528
- // const postUser = client.createRequest<{ id: string }, { name: string }>()({
529
- // method: "POST",
530
- // endpoint: "/users",
531
- // });
532
- //
533
- // const patchUser = client.createRequest<{ id: string }, { name: string }>()({
534
- // method: "PATCH",
535
- // endpoint: "/users/:id",
536
- // });
537
- //
538
- // const mappedReq = client
539
- // .createRequest<{ id: string }, { name: string }>()({
540
- // method: "POST",
541
- // endpoint: "/users",
542
- // })
543
- // .setDataMapper((data) => {
544
- // const formData = new FormData();
545
- // formData.append("key", data.name);
546
- // return formData;
547
- // });
548
- //
549
- // // ================>
550
- //
551
- // // OK
552
- // getUsers.send({ queryParams: "" });
553
- // getUsers.setQueryParams("").send();
554
- // // Fail
555
- // getUsers.send({ data: "" });
556
- // getUsers.send({ params: "" });
557
- // getUsers.setQueryParams("").send({ queryParams: "" });
558
- //
559
- // // ================>
560
- //
561
- // // OK
562
- // getUser.send({ params: { id: "" }, queryParams: "" });
563
- // getUser.setParams({ id: "" }).send({ queryParams: "" });
564
- // // Fail
565
- // getUser.send({ queryParams: "" });
566
- // getUser.send();
567
- // getUser.setParams({ id: "" }).send({ params: { id: "" } });
568
- // getUser.setParams(null).send();
569
- // getUser.send({ params: { id: null } }); // <----- Should fail
570
- //
571
- // // ================>
572
- //
573
- // // OK
574
- // postUser.send({ data: { name: "" } });
575
- // postUser.setData({ name: "" }).send();
576
- // // Fail
577
- // postUser.send({ queryParams: "" });
578
- // postUser.send({ data: null }); // <------ Should fail
579
- // postUser.setData(null).send();
580
- // postUser.send();
581
- // postUser.setData({ name: "" }).send({ data: { name: "" } });
582
- //
583
- // // ================>
584
- //
585
- // // OK
586
- // patchUser.send({ params: { id: "" }, data: { name: "" } });
587
- // patchUser.setParams({ id: "" }).setData({ name: "" }).send();
588
- // // Fail
589
- // patchUser.send({ queryParams: "" });
590
- // patchUser.send({ data: null });
591
- // patchUser.setData(null).send();
592
- // patchUser.send();
593
- // patchUser
594
- // .setParams({ id: "" })
595
- // .setData({ name: "" })
596
- // .send({ data: { name: "" } });
597
- // patchUser
598
- // .setParams({ id: "" })
599
- // .setData({ name: "" })
600
- // .send({ params: { id: "" } });
601
- //
602
- // // ================>
603
- //
604
- // // OK
605
- // mappedReq.send({ data: { name: "" } });
606
- // mappedReq.setData({ name: "" }).send();
607
- // // Fail
608
- // mappedReq.send({ queryParams: "" });
609
- // mappedReq.send({ data: undefined }); // <---- should fail
610
- // mappedReq.setData(null).send();
611
- // mappedReq.setData(null).send({ data: null, queryParams: () => null });
612
- // mappedReq.send();
613
- // mappedReq.send({ data: new FormData() });
614
- // mappedReq.setData({ name: "" }).send({ data: { name: "" } });
619
+ static fromJSON = <
620
+ NewResponse,
621
+ NewPayload,
622
+ NewQueryParams,
623
+ NewLocalError,
624
+ NewEndpoint extends string,
625
+ NewClient extends ClientInstance,
626
+ NewHasPayload extends true | false = false,
627
+ NewHasParams extends true | false = false,
628
+ NewHasQuery extends true | false = false,
629
+ >(
630
+ client: NewClient,
631
+ json: RequestJSON<
632
+ Request<
633
+ NewResponse,
634
+ NewPayload,
635
+ NewQueryParams,
636
+ NewLocalError,
637
+ NewEndpoint,
638
+ NewClient,
639
+ NewHasPayload,
640
+ NewHasParams,
641
+ NewHasQuery
642
+ >
643
+ >,
644
+ ) => {
645
+ return new Request<
646
+ NewResponse,
647
+ NewPayload,
648
+ NewQueryParams,
649
+ NewLocalError,
650
+ NewEndpoint,
651
+ NewClient,
652
+ NewHasPayload,
653
+ NewHasParams,
654
+ NewHasQuery
655
+ >(client, json.requestOptions, json);
656
+ };
657
+ }