@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,83 +1,101 @@
1
1
  import {
2
2
  NullableKeys,
3
- NegativeTypes,
3
+ EmptyTypes,
4
4
  ExtractParamsType,
5
5
  ExtractPayloadType,
6
- ExtractRequestQueryParamsType,
7
6
  ExtractAdapterType,
8
7
  ExtractEndpointType,
9
- ExtractHasDataType,
8
+ ExtractHasPayloadType,
10
9
  ExtractHasParamsType,
11
10
  ExtractHasQueryParamsType,
12
11
  ExtractErrorType,
13
12
  ExtractResponseType,
14
13
  HttpMethodsType,
15
- } from "types";
16
- import { Request } from "request";
17
- import {
18
- ResponseReturnType,
19
- QueryParamsType,
20
- ProgressType,
14
+ ExtractQueryParamsType,
21
15
  ExtractAdapterOptionsType,
22
- AdapterType,
23
16
  ExtractAdapterMethodType,
24
- } from "adapter";
25
- import { RequestEventType, ResponseDetailsType } from "managers";
17
+ TypeWithDefaults,
18
+ } from "types";
19
+ import { Request } from "request";
20
+ import { RequestResponseType, ResponseSuccessType, ResponseErrorType } from "adapter";
21
+ import { RequestEventType, RequestProgressEventType, RequestResponseEventType } from "managers";
22
+ import { ClientInstance } from "client";
26
23
 
27
- // Progress
28
- export type AdapterProgressEventType = { total: number; loaded: number };
29
- export type AdapterProgressType = {
30
- progress: number;
31
- timeLeft: number;
32
- sizeLeft: number;
24
+ // Instance
25
+
26
+ export type RequestInstanceProperties = {
27
+ response?: any;
28
+ payload?: any;
29
+ error?: any;
30
+ client?: ClientInstance;
31
+ queryParams?: any;
32
+ endpoint?: string;
33
+ hasParams?: boolean;
34
+ hasQueryParams?: boolean;
35
+ hasPayload?: boolean;
33
36
  };
34
37
 
35
- // Dump
38
+ export type RequestInstance<
39
+ RequestProperties extends RequestInstanceProperties = {
40
+ response?: any;
41
+ payload?: any;
42
+ queryParams?: any;
43
+ error?: any;
44
+ client?: ClientInstance;
45
+ },
46
+ > = Request<
47
+ TypeWithDefaults<RequestProperties, "response", any>,
48
+ TypeWithDefaults<RequestProperties, "payload", any>,
49
+ TypeWithDefaults<RequestProperties, "queryParams", any>,
50
+ TypeWithDefaults<RequestProperties, "error", any>,
51
+ TypeWithDefaults<RequestProperties, "endpoint", any>,
52
+ TypeWithDefaults<RequestProperties, "client", ClientInstance>,
53
+ TypeWithDefaults<RequestProperties, "hasParams", any>,
54
+ TypeWithDefaults<RequestProperties, "hasQueryParams", any>,
55
+ TypeWithDefaults<RequestProperties, "hasPayload", any>
56
+ >;
57
+
58
+ // Progress
59
+ export type ProgressEventType = { total: number; loaded: number };
36
60
 
37
61
  /**
38
62
  * Dump of the request used to later recreate it
39
63
  */
40
- export type RequestJSON<
41
- Request extends RequestInstance,
42
- // Bellow generics provided only to overcome the typescript bugs
43
- AdapterOptions = unknown,
44
- QueryParams = QueryParamsType,
45
- Params = ExtractParamsType<Request>,
46
- > = {
64
+ export type RequestJSON<Request extends RequestInstance> = {
47
65
  requestOptions: RequestOptionsType<
48
- string,
49
- AdapterOptions | ExtractAdapterType<Request>,
66
+ ExtractEndpointType<Request>,
67
+ ExtractAdapterOptionsType<ExtractAdapterType<Request>>,
50
68
  ExtractAdapterMethodType<ExtractAdapterType<Request>>
51
69
  >;
52
- endpoint: string;
70
+ endpoint: ExtractEndpointType<Request>;
53
71
  method: ExtractAdapterMethodType<ExtractAdapterType<Request>>;
54
72
  headers?: HeadersInit;
55
73
  auth: boolean;
56
74
  cancelable: boolean;
57
75
  retry: number;
58
76
  retryTime: number;
59
- garbageCollection: number;
60
- cache: boolean;
61
77
  cacheTime: number;
78
+ cache: boolean;
79
+ staleTime: number;
62
80
  queued: boolean;
63
81
  offline: boolean;
64
82
  disableResponseInterceptors: boolean | undefined;
65
83
  disableRequestInterceptors: boolean | undefined;
66
- options?: AdapterOptions | ExtractAdapterOptionsType<ExtractAdapterType<Request>>;
67
- data: PayloadType<ExtractPayloadType<Request>>;
68
- params: Params | NegativeTypes;
69
- queryParams: QueryParams | NegativeTypes;
84
+ options?: ExtractAdapterOptionsType<ExtractAdapterType<Request>>;
85
+ payload: PayloadType<ExtractPayloadType<Request>>;
86
+ params: ExtractParamsType<Request> | EmptyTypes;
87
+ queryParams: ExtractQueryParamsType<Request> | EmptyTypes;
70
88
  abortKey: string;
71
89
  cacheKey: string;
72
- queueKey: string;
73
- effectKey: string;
90
+ queryKey: string;
74
91
  used: boolean;
75
92
  updatedAbortKey: boolean;
76
93
  updatedCacheKey: boolean;
77
- updatedQueueKey: boolean;
78
- updatedEffectKey: boolean;
94
+ updatedQueryKey: boolean;
79
95
  deduplicate: boolean;
80
- deduplicateTime: number;
96
+ deduplicateTime: number | null;
97
+ isMockerEnabled: boolean;
98
+ hasMock: boolean;
81
99
  };
82
100
 
83
101
  // Request
@@ -85,11 +103,7 @@ export type RequestJSON<
85
103
  /**
86
104
  * Configuration options for request creation
87
105
  */
88
- export type RequestOptionsType<
89
- GenericEndpoint extends string,
90
- AdapterOptions extends Record<string, any>,
91
- RequestMethods = HttpMethodsType,
92
- > = {
106
+ export type RequestOptionsType<GenericEndpoint, AdapterOptions, RequestMethods = HttpMethodsType> = {
93
107
  /**
94
108
  * Determine the endpoint for request request
95
109
  */
@@ -103,7 +117,8 @@ export type RequestOptionsType<
103
117
  */
104
118
  auth?: boolean;
105
119
  /**
106
- * Request method GET | POST | PATCH | PUT | DELETE or set of method names handled by adapter
120
+ * Request method picked from method names handled by adapter
121
+ * With default adapter it is GET | POST | PATCH | PUT | DELETE
107
122
  */
108
123
  method?: RequestMethods;
109
124
  /**
@@ -121,7 +136,7 @@ export type RequestOptionsType<
121
136
  /**
122
137
  * Should we trigger garbage collection or leave data in memory
123
138
  */
124
- garbageCollection?: number;
139
+ cacheTime?: number;
125
140
  /**
126
141
  * Should we save the response to cache
127
142
  */
@@ -129,7 +144,7 @@ export type RequestOptionsType<
129
144
  /**
130
145
  * Time for which the cache is considered up-to-date
131
146
  */
132
- cacheTime?: number;
147
+ staleTime?: number;
133
148
  /**
134
149
  * Should the requests from this request be send one-by-one
135
150
  */
@@ -161,11 +176,7 @@ export type RequestOptionsType<
161
176
  /**
162
177
  * Key which will be used to queue requests. Autogenerated by default.
163
178
  */
164
- queueKey?: string;
165
- /**
166
- * Key which will be used to use effects. Autogenerated by default.
167
- */
168
- effectKey?: string;
179
+ queryKey?: string;
169
180
  /**
170
181
  * Should we deduplicate two requests made at the same time into one
171
182
  */
@@ -176,25 +187,26 @@ export type RequestOptionsType<
176
187
  deduplicateTime?: number;
177
188
  };
178
189
 
179
- export type PayloadMapperType<Payload> = <NewDataType>(data: Payload) => NewDataType;
190
+ export type PayloadMapperType<Payload> = <NewDataType>(payload: Payload) => NewDataType;
180
191
 
181
- export type PayloadType<Payload> = Payload | NegativeTypes;
192
+ export type PayloadType<Payload> = Payload | EmptyTypes;
182
193
 
183
- export type RequestCurrentType<
194
+ export type RequestConfigurationType<
184
195
  Payload,
196
+ Params,
185
197
  QueryParams,
186
198
  GenericEndpoint extends string,
187
199
  AdapterOptions,
188
- MethodsType = HttpMethodsType,
200
+ MethodsType,
189
201
  > = {
190
202
  used?: boolean;
191
- params?: ExtractRouteParams<GenericEndpoint> | NegativeTypes;
192
- queryParams?: QueryParams | NegativeTypes;
193
- data?: PayloadType<Payload>;
203
+ params?: Params | EmptyTypes;
204
+ queryParams?: QueryParams | EmptyTypes;
205
+ payload?: PayloadType<Payload>;
194
206
  headers?: HeadersInit;
195
207
  updatedAbortKey?: boolean;
196
208
  updatedCacheKey?: boolean;
197
- updatedQueueKey?: boolean;
209
+ updatedQueryKey?: boolean;
198
210
  updatedEffectKey?: boolean;
199
211
  } & Partial<NullableKeys<RequestOptionsType<GenericEndpoint, AdapterOptions, MethodsType>>>;
200
212
 
@@ -202,111 +214,92 @@ export type ParamType = string | number;
202
214
  export type ParamsType = Record<string, ParamType>;
203
215
 
204
216
  export type ExtractRouteParams<T extends string> = string extends T
205
- ? NegativeTypes
206
- : T extends `${string}:${infer Param}/${infer Rest}`
207
- ? { [k in Param | keyof ExtractRouteParams<Rest>]: ParamType }
208
- : T extends `${string}:${infer Param}`
209
- ? { [k in Param]: ParamType }
210
- : NegativeTypes;
211
-
212
- export type FetchOptionsType<AdapterOptions> = Omit<
213
- Partial<RequestOptionsType<string, AdapterOptions>>,
214
- "endpoint" | "method"
215
- >;
216
-
217
- /**
218
- * It will check if the query params are already set
219
- */
220
- export type FetchQueryParamsType<QueryParams, HasQuery extends true | false = false> = HasQuery extends true
221
- ? { queryParams?: NegativeTypes }
222
- : {
223
- queryParams?: QueryParams;
224
- };
217
+ ? EmptyTypes
218
+ : // eslint-disable-next-line @typescript-eslint/no-unused-vars
219
+ T extends `${string}:${infer Param}/${infer Rest}`
220
+ ? { [k in Param | keyof ExtractRouteParams<Rest>]: ParamType }
221
+ : // eslint-disable-next-line @typescript-eslint/no-unused-vars
222
+ T extends `${string}:${infer Param}`
223
+ ? { [k in Param]: ParamType }
224
+ : EmptyTypes;
225
225
 
226
226
  /**
227
227
  * If the request endpoint parameters are not filled it will throw an error
228
228
  */
229
- export type FetchParamsType<
230
- Endpoint extends string,
231
- HasParams extends true | false,
232
- > = ExtractRouteParams<Endpoint> extends NegativeTypes
233
- ? { params?: NegativeTypes }
229
+ export type FetchParamsType<Params, HasParams extends true | false> = Params extends EmptyTypes | void | never
230
+ ? { params?: EmptyTypes }
234
231
  : HasParams extends true
235
- ? { params?: NegativeTypes }
236
- : { params: NonNullable<ExtractRouteParams<Endpoint>> };
232
+ ? { params?: EmptyTypes }
233
+ : { params: Params };
237
234
 
238
235
  /**
239
236
  * If the request data is not filled it will throw an error
240
237
  */
241
- export type FetchPayloadType<Payload, HasData extends true | false> = Payload extends NegativeTypes
242
- ? { data?: NegativeTypes }
243
- : HasData extends true
244
- ? { data?: NegativeTypes }
245
- : { data: NonNullable<Payload> };
238
+ export type FetchPayloadType<Payload, HasPayload extends true | false> = Payload extends EmptyTypes | void | never
239
+ ? { payload?: EmptyTypes }
240
+ : HasPayload extends true
241
+ ? { payload?: EmptyTypes }
242
+ : { payload: Payload };
246
243
 
247
- export type RequestQueueOptions = {
244
+ /**
245
+ * It will check if the query params are already set
246
+ */
247
+ export type FetchQueryParamsType<QueryParams, HasQuery extends true | false = false> = HasQuery extends true
248
+ ? { queryParams?: EmptyTypes | undefined }
249
+ : HasQuery extends true
250
+ ? { queryParams?: EmptyTypes }
251
+ : QueryParams extends EmptyTypes | void | never
252
+ ? { queryParams?: QueryParams }
253
+ : {
254
+ queryParams: QueryParams;
255
+ };
256
+
257
+ export type RequestDynamicSendOptionsType<Request extends RequestInstance> = Omit<
258
+ Partial<RequestOptionsType<string, ExtractAdapterOptionsType<ExtractAdapterType<Request>>>>,
259
+ "params" | "data" | "endpoint" | "method"
260
+ > & {
248
261
  dispatcherType?: "auto" | "fetch" | "submit";
249
262
  };
250
263
 
251
264
  // Request making
252
265
 
253
266
  export type RequestSendOptionsType<Request extends RequestInstance> = FetchQueryParamsType<
254
- ExtractRequestQueryParamsType<Request>,
267
+ ExtractQueryParamsType<Request>,
255
268
  ExtractHasQueryParamsType<Request>
256
269
  > &
257
- FetchParamsType<ExtractEndpointType<Request>, ExtractHasParamsType<Request>> &
258
- FetchPayloadType<ExtractPayloadType<Request>, ExtractHasDataType<Request>> &
259
- Omit<FetchOptionsType<ExtractAdapterType<Request>>, "params" | "data"> &
260
- FetchSendActionsType<Request> &
261
- RequestQueueOptions;
270
+ FetchParamsType<ExtractParamsType<Request>, ExtractHasParamsType<Request>> &
271
+ FetchPayloadType<ExtractPayloadType<Request>, ExtractHasPayloadType<Request>> &
272
+ FetchQueryParamsType<ExtractQueryParamsType<Request>, ExtractHasQueryParamsType<Request>> &
273
+ RequestSendActionsType<Request> &
274
+ RequestDynamicSendOptionsType<Request>;
262
275
 
263
- export type FetchSendActionsType<Request extends RequestInstance> = {
264
- onSettle?: (requestId: string, request: Request) => void;
265
- onRequestStart?: (details: RequestEventType<Request>) => void;
266
- onResponseStart?: (details: RequestEventType<Request>) => void;
267
- onUploadProgress?: (values: ProgressType, details: RequestEventType<Request>) => void;
268
- onDownloadProgress?: (values: ProgressType, details: RequestEventType<Request>) => void;
269
- onResponse?: (
270
- response: ResponseReturnType<ExtractResponseType<Request>, ExtractErrorType<Request>, ExtractAdapterType<Request>>,
271
- details: ResponseDetailsType,
272
- ) => void;
273
- onRemove?: (details: RequestEventType<Request>) => void;
276
+ export type RequestSendActionsType<Request extends RequestInstance> = {
277
+ onBeforeSent?: (eventData: RequestEventType<Request>) => void;
278
+ onRequestStart?: (eventData: RequestEventType<Request>) => void;
279
+ onResponseStart?: (eventData: RequestEventType<Request>) => void;
280
+ onUploadProgress?: (eventData: RequestProgressEventType<Request>) => void;
281
+ onDownloadProgress?: (eventData: RequestProgressEventType<Request>) => void;
282
+ onResponse?: (eventData: RequestResponseEventType<Request>) => void;
283
+ onRemove?: (eventData: RequestEventType<Request>) => void;
274
284
  };
275
285
 
286
+ type IsNegativeType<T> = void extends T
287
+ ? EmptyTypes
288
+ : undefined extends T
289
+ ? EmptyTypes
290
+ : null extends T
291
+ ? EmptyTypes
292
+ : T;
293
+
276
294
  // If no data or params provided - options should be optional. If either data or params are provided - mandatory.
277
295
  export type RequestSendType<Request extends RequestInstance> =
278
- RequestSendOptionsType<Request>["data"] extends NegativeTypes
279
- ? RequestSendOptionsType<Request>["params"] extends NegativeTypes
280
- ? (
281
- options?: RequestSendOptionsType<Request>,
282
- ) => Promise<
283
- ResponseReturnType<ExtractResponseType<Request>, ExtractErrorType<Request>, ExtractAdapterType<Request>>
284
- >
285
- : (
286
- options: RequestSendOptionsType<Request>,
287
- ) => Promise<
288
- ResponseReturnType<ExtractResponseType<Request>, ExtractErrorType<Request>, ExtractAdapterType<Request>>
289
- >
290
- : (
291
- options: RequestSendOptionsType<Request>,
292
- ) => Promise<
293
- ResponseReturnType<ExtractResponseType<Request>, ExtractErrorType<Request>, ExtractAdapterType<Request>>
294
- >;
295
-
296
- // Instance
297
-
298
- export type RequestInstance = Request<
299
- any,
300
- any,
301
- any,
302
- any,
303
- any,
304
- any,
305
- AdapterType<any, any, any, any, any>,
306
- any,
307
- any,
308
- any
309
- >;
296
+ IsNegativeType<RequestSendOptionsType<Request>["payload"]> extends EmptyTypes | void | never
297
+ ? IsNegativeType<RequestSendOptionsType<Request>["params"]> extends EmptyTypes | void | never
298
+ ? IsNegativeType<RequestSendOptionsType<Request>["queryParams"]> extends EmptyTypes | void | never
299
+ ? (options?: RequestSendOptionsType<Request>) => Promise<RequestResponseType<Request>>
300
+ : (options: RequestSendOptionsType<Request>) => Promise<RequestResponseType<Request>>
301
+ : (options: RequestSendOptionsType<Request>) => Promise<RequestResponseType<Request>>
302
+ : (options: RequestSendOptionsType<Request>) => Promise<RequestResponseType<Request>>;
310
303
 
311
304
  // Mappers
312
305
 
@@ -315,8 +308,11 @@ export type RequestMapper<Request extends RequestInstance, NewRequest extends Re
315
308
  requestId: string,
316
309
  ) => NewRequest | Promise<NewRequest>;
317
310
 
318
- export type ResponseMapper<Request extends RequestInstance, NewResponse, NewError> = (
319
- response: ResponseReturnType<ExtractResponseType<Request>, ExtractErrorType<Request>, ExtractAdapterType<Request>>,
320
- ) =>
321
- | ResponseReturnType<NewResponse, NewError, ExtractAdapterType<Request>>
322
- | Promise<ResponseReturnType<NewResponse, NewError, ExtractAdapterType<Request>>>;
311
+ export type ResponseMapper<
312
+ Request extends RequestInstance,
313
+ MappedResponse extends ResponseSuccessType<any, any> | ResponseErrorType<any, any>,
314
+ > = (
315
+ response:
316
+ | ResponseSuccessType<ExtractResponseType<Request>, ExtractAdapterType<Request>>
317
+ | ResponseErrorType<ExtractErrorType<Request>, ExtractAdapterType<Request>>,
318
+ ) => MappedResponse | Promise<MappedResponse>;
@@ -1,6 +1,6 @@
1
- import { ProgressType, ResponseReturnType, getErrorMessage } from "adapter";
2
- import { AdapterProgressEventType, RequestInstance, RequestJSON, RequestSendOptionsType } from "request";
3
- import { HttpMethodsEnum } from "constants/http.constants";
1
+ import { ProgressType, ResponseType, getErrorMessage } from "adapter";
2
+ import { ProgressEventType, RequestInstance, RequestJSON, RequestSendOptionsType } from "request";
3
+ import { HttpMethods } from "constants/http.constants";
4
4
  import { canRetryRequest, Dispatcher } from "dispatcher";
5
5
  import { ExtractAdapterType, ExtractErrorType, ExtractResponseType } from "types";
6
6
 
@@ -16,7 +16,7 @@ export const stringifyKey = (value: unknown): string => {
16
16
  }
17
17
  };
18
18
 
19
- export const getProgressValue = ({ loaded, total }: AdapterProgressEventType): number => {
19
+ export const getProgressValue = ({ loaded, total }: ProgressEventType): number => {
20
20
  if (!loaded || !total) return 0;
21
21
  return Number(((loaded * 100) / total).toFixed(0));
22
22
  };
@@ -24,7 +24,7 @@ export const getProgressValue = ({ loaded, total }: AdapterProgressEventType): n
24
24
  export const getRequestEta = (
25
25
  startDate: Date,
26
26
  progressDate: Date,
27
- { total, loaded }: AdapterProgressEventType,
27
+ { total, loaded }: ProgressEventType,
28
28
  ): { sizeLeft: number; timeLeft: number | null } => {
29
29
  const timeElapsed = +progressDate - +startDate || 1;
30
30
  const uploadSpeed = loaded / timeElapsed;
@@ -39,7 +39,7 @@ export const getRequestEta = (
39
39
  export const getProgressData = (
40
40
  requestStartTime: Date,
41
41
  progressDate: Date,
42
- progressEvent: AdapterProgressEventType,
42
+ progressEvent: ProgressEventType,
43
43
  ): ProgressType => {
44
44
  const { total, loaded } = progressEvent;
45
45
  if (Number.isNaN(total) || Number.isNaN(loaded)) {
@@ -94,16 +94,17 @@ export const getRequestKey = (
94
94
  */
95
95
  const methodKey = stringifyKey(request.method);
96
96
  const endpointKey = useInitialValues ? request.requestOptions.endpoint : stringifyKey(request.endpoint);
97
+ const queryParamsKey = useInitialValues ? "" : stringifyKey(request.queryParams);
97
98
 
98
- return `${methodKey}_${endpointKey}`;
99
+ return `${methodKey}_${endpointKey}_${queryParamsKey}`;
99
100
  };
100
101
 
101
102
  export const getRequestDispatcher = <Request extends RequestInstance>(
102
103
  request: Request,
103
104
  dispatcherType: "auto" | "fetch" | "submit" = "auto",
104
- ): [Dispatcher, boolean] => {
105
+ ): [Dispatcher<ExtractAdapterType<Request>>, isFetchDispatcher: boolean] => {
105
106
  const { fetchDispatcher, submitDispatcher } = request.client;
106
- const isGet = request.method === HttpMethodsEnum.get;
107
+ const isGet = request.method === HttpMethods.GET;
107
108
  const isFetchDispatcher = (dispatcherType === "auto" && isGet) || dispatcherType === "fetch";
108
109
  const dispatcher = isFetchDispatcher ? fetchDispatcher : submitDispatcher;
109
110
 
@@ -114,53 +115,53 @@ export const sendRequest = <Request extends RequestInstance>(
114
115
  request: Request,
115
116
  options?: RequestSendOptionsType<Request>,
116
117
  ) => {
117
- const { requestManager } = request.client;
118
+ const { client } = request;
119
+ const { requestManager } = client;
118
120
  const [dispatcher] = getRequestDispatcher(request, options?.dispatcherType);
119
121
 
120
122
  return new Promise<
121
- ResponseReturnType<ExtractResponseType<Request>, ExtractErrorType<Request>, ExtractAdapterType<Request>>
123
+ ResponseType<ExtractResponseType<Request>, ExtractErrorType<Request>, ExtractAdapterType<Request>>
122
124
  >((resolve) => {
123
125
  let isResolved = false;
124
126
  const requestId = dispatcher.add(request);
125
- options?.onSettle?.(requestId, request);
127
+ options?.onBeforeSent?.({ requestId, request });
126
128
 
127
- const unmountRequestStart = requestManager.events.onRequestStartById<Request>(requestId, (...props) =>
128
- options?.onRequestStart?.(...props),
129
+ const unmountRequestStart = requestManager.events.onRequestStartById<Request>(requestId, (data) =>
130
+ options?.onRequestStart?.(data),
129
131
  );
130
132
 
131
- const unmountResponseStart = requestManager.events.onResponseStartById<Request>(requestId, (...props) =>
132
- options?.onResponseStart?.(...props),
133
+ const unmountResponseStart = requestManager.events.onResponseStartById<Request>(requestId, (data) =>
134
+ options?.onResponseStart?.(data),
133
135
  );
134
136
 
135
- const unmountUpload = requestManager.events.onUploadProgressById<Request>(requestId, (...props) =>
136
- options?.onUploadProgress?.(...props),
137
+ const unmountUpload = requestManager.events.onUploadProgressById<Request>(requestId, (data) =>
138
+ options?.onUploadProgress?.(data),
137
139
  );
138
140
 
139
- const unmountDownload = requestManager.events.onDownloadProgressById<Request>(requestId, (...props) =>
140
- options?.onDownloadProgress?.(...props),
141
+ const unmountDownload = requestManager.events.onDownloadProgressById<Request>(requestId, (data) =>
142
+ options?.onDownloadProgress?.(data),
141
143
  );
142
144
 
143
145
  // When resolved
144
- const unmountResponse = requestManager.events.onResponseById<
145
- ExtractResponseType<Request>,
146
- ExtractErrorType<Request>,
147
- ExtractAdapterType<Request>
148
- >(requestId, (response, details) => {
146
+ const unmountResponse = requestManager.events.onResponseById<Request>(requestId, (values) => {
147
+ const { details, response } = values;
149
148
  isResolved = true;
150
149
 
151
- const mapping = request.responseMapper?.(response);
150
+ const mapping = request.unstable_responseMapper?.(
151
+ response as ResponseType<any, any, ExtractAdapterType<Request>>,
152
+ );
152
153
 
153
154
  const isOfflineStatus = request.offline && details.isOffline;
154
155
  const willRetry = canRetryRequest(details.retries, request.retry);
155
156
 
156
- const handleResponse = (success: boolean, data: any) => {
157
+ const handleResponse = (success: boolean, data: ResponseType<any, any, ExtractAdapterType<Request>>) => {
157
158
  // When going offline we can't handle the request as it will be postponed to later resolve
158
159
  if (!success && isOfflineStatus) return;
159
160
 
160
161
  // When request is in retry mode we need to listen for retries end
161
162
  if (!success && willRetry) return;
162
163
 
163
- options?.onResponse?.(data, details);
164
+ options?.onResponse?.(values);
164
165
  resolve(data);
165
166
 
166
167
  // Unmount Listeners
@@ -174,14 +175,14 @@ export const sendRequest = <Request extends RequestInstance>(
174
175
  const responseData = await mapping;
175
176
 
176
177
  const { success } = responseData;
177
- handleResponse(success, responseData);
178
+ handleResponse(success, responseData as ResponseType<any, any, ExtractAdapterType<Request>>);
178
179
  })();
179
180
  }
180
181
  // For sync mapping operations we should not use async actions
181
182
  else {
182
183
  const data = mapping || response;
183
184
  const { success } = data;
184
- handleResponse(success, data);
185
+ handleResponse(success, data as ResponseType<any, any, ExtractAdapterType<Request>>);
185
186
  }
186
187
  });
187
188
 
@@ -192,9 +193,11 @@ export const sendRequest = <Request extends RequestInstance>(
192
193
  resolve({
193
194
  data: null,
194
195
  status: null,
195
- success: null,
196
+ success: false,
196
197
  error: getErrorMessage("deleted") as unknown as ExtractErrorType<Request>,
197
- extra: request.client.defaultExtra,
198
+ extra: request.client.adapter.defaultExtra,
199
+ requestTimestamp: +new Date(),
200
+ responseTimestamp: +new Date(),
198
201
  });
199
202
 
200
203
  // Unmount Listeners
@@ -0,0 +1,63 @@
1
+ import { Adapter, AdapterInstance } from "adapter";
2
+
3
+ export type ExtractAdapterOptionsType<T> =
4
+ T extends Adapter<infer O, any, any, any, any, any, any, any, any, any, any> ? O : never;
5
+ export type ExtractAdapterMethodType<T> =
6
+ T extends Adapter<any, infer M, any, any, any, any, any, any, any, any, any> ? M : never;
7
+ export type ExtractAdapterStatusType<T> =
8
+ T extends Adapter<any, any, infer S, any, any, any, any, any, any, any, any> ? S : never;
9
+ export type ExtractAdapterExtraType<T> =
10
+ T extends Adapter<any, any, any, infer A, any, any, any, any, any, any, any> ? A : never;
11
+ export type ExtractAdapterQueryParamsType<T> =
12
+ T extends Adapter<any, any, any, any, infer Q, any, any, any, any, any, any> ? Q : never;
13
+ export type ExtractAdapterDefaultQueryParamsType<T> =
14
+ T extends Adapter<any, any, any, any, any, infer Q, any, any, any, any, any> ? Q : never;
15
+ export type ExtractAdapterEndpointType<T> =
16
+ T extends Adapter<any, any, any, any, any, any, infer E, any, any, any, any> ? E : never;
17
+ export type ExtractAdapterEndpointMapperType<T> =
18
+ T extends Adapter<any, any, any, any, any, any, any, infer EM, any, any, any> ? EM : never;
19
+ export type ExtractAdapterQueryParamsMapperType<T> =
20
+ T extends Adapter<any, any, any, any, any, any, any, any, infer QPM, any, any> ? QPM : never;
21
+ export type ExtractAdapterHeaderMapperType<T> =
22
+ T extends Adapter<any, any, any, any, any, any, any, any, any, infer HM, any> ? HM : never;
23
+ export type ExtractAdapterPayloadMapperType<T> =
24
+ T extends Adapter<any, any, any, any, any, any, any, any, any, any, infer PM> ? PM : never;
25
+
26
+ // Special type only for selecting appropriate AdapterType union version (check FirebaseAdapterType).
27
+ export type ExtractUnionAdapter<
28
+ AdapterType extends AdapterInstance,
29
+ Values extends {
30
+ method?: any;
31
+ options?: any;
32
+ status?: any;
33
+ extra?: any;
34
+ queryParams?: any;
35
+ endpointType?: any;
36
+ defaultQueryParams?: any;
37
+ },
38
+ > =
39
+ Extract<
40
+ AdapterType,
41
+ Adapter<
42
+ Values["options"],
43
+ Values["method"],
44
+ Values["status"],
45
+ Values["extra"],
46
+ Values["queryParams"],
47
+ Values["defaultQueryParams"],
48
+ Values["endpointType"]
49
+ >
50
+ > extends AdapterInstance
51
+ ? Extract<
52
+ AdapterType,
53
+ Adapter<
54
+ Values["options"],
55
+ Values["method"],
56
+ Values["status"],
57
+ Values["extra"],
58
+ Values["queryParams"],
59
+ Values["defaultQueryParams"],
60
+ Values["endpointType"]
61
+ >
62
+ >
63
+ : never;
@@ -1,4 +1,4 @@
1
- import { Client } from "client";
1
+ import { Client, ClientInstance } from "client";
2
2
 
3
- export type ExtractClientGlobalError<T> = T extends Client<infer G, any> ? G : never;
4
- export type ExtractClientAdapterType<T> = T extends Client<any, infer A> ? A : never;
3
+ export type ExtractClientGlobalError<T extends ClientInstance> = T extends Client<infer P, any> ? P : never;
4
+ export type ExtractClientAdapterType<T extends ClientInstance> = T extends Client<any, infer P> ? P : never;