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