@hyper-fetch/core 8.1.1 → 8.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +137 -52
- package/__tests__/e2e/e2e.advanced.spec.ts +7 -7
- package/__tests__/features/adapter/adapter.base.spec.ts +2 -1
- package/__tests__/features/adapter/adapter.bindings.spec.ts +4 -4
- package/__tests__/features/adapter/adapter.browser.spec.ts +0 -1
- package/__tests__/features/adapter/adapter.server.spec.ts +4 -5
- package/__tests__/features/adapter/adapter.utils.spec.ts +6 -7
- package/__tests__/features/cache/cache.base.spec.ts +7 -7
- package/__tests__/features/cache/cache.events.spec.ts +15 -15
- package/__tests__/features/cache/cache.garbage-collector.spec.ts +18 -18
- package/__tests__/features/cache/cache.lazy-storage.spec.ts +8 -8
- package/__tests__/features/cache/cache.modes.spec.ts +7 -6
- package/__tests__/features/cache/cache.scoping.spec.ts +12 -8
- package/__tests__/features/cache/cache.typescript.spec.ts +2 -2
- package/__tests__/features/cache/cache.utils.spec.ts +14 -14
- package/__tests__/features/client/client.auth.spec.ts +0 -1
- package/__tests__/features/client/client.base.spec.ts +2 -3
- package/__tests__/features/client/client.from-json.spec.ts +0 -1
- package/__tests__/features/client/client.hydration.spec.ts +5 -5
- package/__tests__/features/client/client.interceptor.spec.ts +3 -3
- package/__tests__/features/client/client.methods.spec.ts +5 -5
- package/__tests__/features/client/client.middleware.spec.ts +2 -2
- package/__tests__/features/client/client.utils.spec.ts +16 -15
- package/__tests__/features/dispatcher/dispatcher.base.spec.ts +3 -3
- package/__tests__/features/dispatcher/dispatcher.custom-storage.spec.ts +4 -5
- package/__tests__/features/dispatcher/dispatcher.events.spec.ts +4 -4
- package/__tests__/features/dispatcher/dispatcher.queue.spec.ts +13 -13
- package/__tests__/features/dispatcher/dispatcher.requests.spec.ts +10 -10
- package/__tests__/features/dispatcher/dispatcher.utils.spec.ts +35 -8
- package/__tests__/features/managers/app/app.manager.base.spec.ts +2 -3
- package/__tests__/features/managers/logger/logger.base.spec.ts +1 -2
- package/__tests__/features/managers/request/request.manager.base.spec.ts +8 -9
- package/__tests__/features/managers/request/request.manager.events.spec.ts +1 -2
- package/__tests__/features/mocker/mocker.base.spec.ts +6 -6
- package/__tests__/features/plugin/plugin.base.spec.ts +1 -2
- package/__tests__/features/request/request.cloning.spec.ts +0 -1
- package/__tests__/features/request/request.deduplicate-defaults.spec.ts +79 -0
- package/__tests__/features/request/request.retry-on-error.spec.ts +1 -2
- package/__tests__/features/request/request.sending.spec.ts +73 -24
- package/__tests__/features/request/request.setters.spec.ts +4 -3
- package/__tests__/features/request/request.typescript.spec.ts +0 -1
- package/__tests__/features/request/request.utils.spec.ts +1 -0
- package/__tests__/features/sdk/sdk.base.spec.ts +7 -12
- package/__tests__/features/sdk/sdk.configuration.spec.ts +5 -7
- package/__tests__/features/sdk/sdk.request-fields.spec.ts +80 -0
- package/__tests__/features/sdk/sdk.types.spec.ts +283 -0
- package/__tests__/shared/callbacks.shared.ts +1 -1
- package/__tests__/tsconfig.json +4 -17
- package/__tests__/utils/adapter.utils.ts +1 -2
- package/__tests__/utils/callbacks.utils.ts +1 -2
- package/__tests__/utils/dispatcher.utils.ts +1 -1
- package/__tests__/vitest.setup.ts +1 -1
- package/dist/adapter/adapter.d.ts +22 -5
- package/dist/adapter/adapter.d.ts.map +1 -1
- package/dist/adapter/adapter.types.d.ts +9 -1
- package/dist/adapter/adapter.types.d.ts.map +1 -1
- package/dist/adapter/adapter.utils.d.ts.map +1 -1
- package/dist/cache/cache.d.ts +6 -9
- package/dist/cache/cache.d.ts.map +1 -1
- package/dist/cache/cache.events.d.ts +7 -4
- package/dist/cache/cache.events.d.ts.map +1 -1
- package/dist/cache/cache.types.d.ts +1 -0
- package/dist/cache/cache.types.d.ts.map +1 -1
- package/dist/client/client.create.d.ts +1 -1
- package/dist/client/client.create.d.ts.map +1 -1
- package/dist/client/client.d.ts +8 -4
- package/dist/client/client.d.ts.map +1 -1
- package/dist/client/client.types.d.ts +1 -1
- package/dist/client/client.types.d.ts.map +1 -1
- package/dist/client/client.utils.d.ts.map +1 -1
- package/dist/constants/http.constants.d.ts +5 -1
- package/dist/constants/http.constants.d.ts.map +1 -1
- package/dist/constants/time.constants.d.ts.map +1 -1
- package/dist/dispatcher/dispatcher.d.ts +4 -4
- package/dist/dispatcher/dispatcher.d.ts.map +1 -1
- package/dist/dispatcher/dispatcher.events.d.ts +1 -1
- package/dist/dispatcher/dispatcher.events.d.ts.map +1 -1
- package/dist/dispatcher/dispatcher.utils.d.ts +1 -1
- package/dist/dispatcher/dispatcher.utils.d.ts.map +1 -1
- package/dist/http-adapter/http-adapter.constants.d.ts.map +1 -1
- package/dist/http-adapter/http-adapter.d.ts.map +1 -1
- package/dist/http-adapter/http-adapter.fetch.d.ts +2 -2
- package/dist/http-adapter/http-adapter.fetch.d.ts.map +1 -1
- package/dist/http-adapter/http-adapter.types.d.ts +2 -2
- package/dist/http-adapter/http-adapter.types.d.ts.map +1 -1
- package/dist/http-adapter/http-adapter.utils.d.ts.map +1 -1
- package/dist/index.mjs +2382 -2301
- package/dist/index.mjs.map +1 -1
- package/dist/managers/app/app.manager.constants.d.ts +1 -1
- package/dist/managers/app/app.manager.constants.d.ts.map +1 -1
- package/dist/managers/app/app.manager.d.ts +1 -1
- package/dist/managers/app/app.manager.d.ts.map +1 -1
- package/dist/managers/app/app.manager.events.d.ts +9 -0
- package/dist/managers/app/app.manager.events.d.ts.map +1 -1
- package/dist/managers/logger/logger.manager.d.ts +1 -1
- package/dist/managers/logger/logger.manager.d.ts.map +1 -1
- package/dist/managers/request/request.manager.d.ts.map +1 -1
- package/dist/managers/request/request.manager.events.d.ts +14 -3
- package/dist/managers/request/request.manager.events.d.ts.map +1 -1
- package/dist/mocker/mocker.types.d.ts +1 -0
- package/dist/mocker/mocker.types.d.ts.map +1 -1
- package/dist/plugin/plugin.d.ts +17 -1
- package/dist/plugin/plugin.d.ts.map +1 -1
- package/dist/plugin/plugin.types.d.ts +5 -4
- package/dist/plugin/plugin.types.d.ts.map +1 -1
- package/dist/request/request.d.ts +33 -4
- package/dist/request/request.d.ts.map +1 -1
- package/dist/request/request.hooks.d.ts +2 -2
- package/dist/request/request.hooks.d.ts.map +1 -1
- package/dist/request/request.types.d.ts +92 -5
- package/dist/request/request.types.d.ts.map +1 -1
- package/dist/request/request.utils.d.ts.map +1 -1
- package/dist/sdk/sdk.d.ts +25 -5
- package/dist/sdk/sdk.d.ts.map +1 -1
- package/dist/types/http.types.d.ts +1 -1
- package/dist/types/http.types.d.ts.map +1 -1
- package/dist/types/request.types.d.ts +2 -2
- package/dist/types/request.types.d.ts.map +1 -1
- package/dist/utils/emitter.utils.d.ts +1 -1
- package/dist/utils/emitter.utils.d.ts.map +1 -1
- package/package.json +8 -8
- package/src/adapter/adapter.bindings.ts +14 -14
- package/src/adapter/adapter.ts +28 -10
- package/src/adapter/adapter.types.ts +10 -1
- package/src/adapter/adapter.utils.ts +5 -5
- package/src/cache/cache.events.ts +7 -5
- package/src/cache/cache.ts +14 -17
- package/src/cache/cache.types.ts +1 -0
- package/src/client/client.create.ts +1 -1
- package/src/client/client.ts +14 -9
- package/src/client/client.types.ts +2 -2
- package/src/client/client.utils.ts +3 -2
- package/src/constants/http.constants.ts +5 -0
- package/src/constants/time.constants.ts +1 -1
- package/src/dispatcher/dispatcher.events.ts +1 -2
- package/src/dispatcher/dispatcher.ts +13 -13
- package/src/dispatcher/dispatcher.utils.ts +10 -4
- package/src/http-adapter/http-adapter.constants.ts +1 -0
- package/src/http-adapter/http-adapter.fetch.ts +19 -9
- package/src/http-adapter/http-adapter.ts +2 -1
- package/src/http-adapter/http-adapter.types.ts +3 -2
- package/src/http-adapter/http-adapter.utils.ts +15 -11
- package/src/managers/app/app.manager.constants.ts +2 -1
- package/src/managers/app/app.manager.events.ts +9 -1
- package/src/managers/app/app.manager.ts +1 -1
- package/src/managers/app/app.manager.utils.ts +2 -2
- package/src/managers/logger/logger.manager.ts +1 -2
- package/src/managers/request/request.manager.events.ts +14 -12
- package/src/managers/request/request.manager.ts +4 -4
- package/src/mocker/mocker.ts +2 -2
- package/src/mocker/mocker.types.ts +1 -0
- package/src/plugin/plugin.ts +17 -1
- package/src/plugin/plugin.types.ts +5 -4
- package/src/request/request.hooks.ts +6 -5
- package/src/request/request.ts +77 -34
- package/src/request/request.types.ts +107 -5
- package/src/request/request.utils.ts +17 -16
- package/src/sdk/sdk.ts +79 -23
- package/src/types/http.types.ts +1 -1
- package/src/types/request.types.ts +3 -2
- package/src/utils/emitter.utils.ts +1 -1
- package/src/utils/uuid.utils.ts +1 -1
- package/tsconfig.json +30 -2
- package/vite.config.ts +14 -20
- package/.eslintrc.cjs +0 -12
- package/tsconfig.base.json +0 -7
package/src/request/request.ts
CHANGED
|
@@ -1,3 +1,24 @@
|
|
|
1
|
+
import type { ResponseErrorType, ResponseSuccessType, ResponseType } from "adapter";
|
|
2
|
+
import type { ClientInstance } from "client";
|
|
3
|
+
import { Time } from "constants/time.constants";
|
|
4
|
+
import type { MockerConfigType, MockResponseType } from "mocker";
|
|
5
|
+
import type {
|
|
6
|
+
ExtractAdapterType,
|
|
7
|
+
ExtractClientAdapterType,
|
|
8
|
+
ExtractClientGlobalError,
|
|
9
|
+
ExtractEndpointType,
|
|
10
|
+
ExtractParamsType,
|
|
11
|
+
ExtractPayloadType,
|
|
12
|
+
ExtractQueryParamsType,
|
|
13
|
+
EmptyTypes,
|
|
14
|
+
ExtractAdapterMethodType,
|
|
15
|
+
ExtractAdapterOptionsType,
|
|
16
|
+
HydrateDataType,
|
|
17
|
+
SyncOrAsync,
|
|
18
|
+
} from "types";
|
|
19
|
+
|
|
20
|
+
import type { RequestHooks } from "./request.hooks";
|
|
21
|
+
import { createRequestHooks } from "./request.hooks";
|
|
1
22
|
/* eslint-disable max-lines */
|
|
2
23
|
import type {
|
|
3
24
|
RequestSendOptionsType,
|
|
@@ -15,27 +36,7 @@ import type {
|
|
|
15
36
|
RetryOnErrorCallbackType,
|
|
16
37
|
OptimisticCallback,
|
|
17
38
|
} from "./request.types";
|
|
18
|
-
import type { RequestHooks } from "./request.hooks";
|
|
19
|
-
import { createRequestHooks } from "./request.hooks";
|
|
20
39
|
import { mapResponseForSend, sendRequest, scopeKey } from "./request.utils";
|
|
21
|
-
import type { ClientInstance } from "client";
|
|
22
|
-
import type { ResponseErrorType, ResponseSuccessType, ResponseType } from "adapter";
|
|
23
|
-
import type {
|
|
24
|
-
ExtractAdapterType,
|
|
25
|
-
ExtractClientAdapterType,
|
|
26
|
-
ExtractClientGlobalError,
|
|
27
|
-
ExtractEndpointType,
|
|
28
|
-
ExtractParamsType,
|
|
29
|
-
ExtractPayloadType,
|
|
30
|
-
ExtractQueryParamsType,
|
|
31
|
-
EmptyTypes,
|
|
32
|
-
ExtractAdapterMethodType,
|
|
33
|
-
ExtractAdapterOptionsType,
|
|
34
|
-
HydrateDataType,
|
|
35
|
-
SyncOrAsync,
|
|
36
|
-
} from "types";
|
|
37
|
-
import { Time } from "constants/time.constants";
|
|
38
|
-
import type { MockerConfigType, MockResponseType } from "mocker";
|
|
39
40
|
|
|
40
41
|
type ClientAdapterOptions<C extends ClientInstance> = ExtractAdapterOptionsType<ExtractClientAdapterType<C>>;
|
|
41
42
|
type ClientAdapterMethod<C extends ClientInstance> = ExtractAdapterMethodType<ExtractClientAdapterType<C>>;
|
|
@@ -76,13 +77,13 @@ export class Request<
|
|
|
76
77
|
MutationContext = undefined,
|
|
77
78
|
> {
|
|
78
79
|
endpoint: Endpoint;
|
|
79
|
-
headers?: HeadersInit;
|
|
80
|
+
headers?: HeadersInit = undefined;
|
|
80
81
|
auth: boolean;
|
|
81
82
|
method: ClientAdapterMethod<Client>;
|
|
82
83
|
params: ExtractUrlParams<Endpoint> | EmptyTypes;
|
|
83
84
|
payload: PayloadType<Payload>;
|
|
84
85
|
queryParams: QueryParams | EmptyTypes;
|
|
85
|
-
options?: ClientAdapterOptions<Client> | undefined;
|
|
86
|
+
options?: ClientAdapterOptions<Client> | undefined = undefined;
|
|
86
87
|
cancelable: boolean;
|
|
87
88
|
retry: number;
|
|
88
89
|
retryTime: number;
|
|
@@ -111,23 +112,37 @@ export class Request<
|
|
|
111
112
|
|
|
112
113
|
isMockerEnabled = false;
|
|
113
114
|
|
|
115
|
+
static readonly OPTIONAL_FIELDS = [
|
|
116
|
+
"unstable_mock",
|
|
117
|
+
"unstable_payloadMapper",
|
|
118
|
+
"unstable_requestMapper",
|
|
119
|
+
"unstable_responseMapper",
|
|
120
|
+
"retryOnError",
|
|
121
|
+
"optimistic",
|
|
122
|
+
] as const;
|
|
123
|
+
|
|
124
|
+
// The `= undefined` initializers below are load-bearing. Metro (React Native) compiles
|
|
125
|
+
// class properties in loose mode, which drops field declarations that have no initializer,
|
|
126
|
+
// and the SDK proxy relies on an `in` check to tell request properties apart from deeper
|
|
127
|
+
// API path segments (see OPTIONAL_REQUEST_FIELDS in sdk/sdk.ts).
|
|
114
128
|
unstable_mock?: {
|
|
115
129
|
fn: (options: {
|
|
116
130
|
request: RequestInstance;
|
|
117
131
|
requestId: string;
|
|
118
132
|
}) => MockResponseType<Response, LocalError | ExtractClientGlobalError<Client>, ExtractClientAdapterType<Client>>;
|
|
119
133
|
config: MockerConfigType;
|
|
120
|
-
};
|
|
134
|
+
} = undefined;
|
|
121
135
|
/** @internal */
|
|
122
|
-
unstable_payloadMapper?: PayloadMapperType<Payload
|
|
136
|
+
unstable_payloadMapper?: PayloadMapperType<Payload> = undefined;
|
|
123
137
|
/** @internal */
|
|
124
|
-
unstable_requestMapper?: RequestMapper<any, any
|
|
138
|
+
unstable_requestMapper?: RequestMapper<any, any> = undefined;
|
|
125
139
|
/** @internal */
|
|
126
|
-
unstable_responseMapper?: ResponseMapper<this, ResponseSuccessType<any, any> | ResponseErrorType<any, any
|
|
140
|
+
unstable_responseMapper?: ResponseMapper<this, ResponseSuccessType<any, any> | ResponseErrorType<any, any>> =
|
|
141
|
+
undefined;
|
|
127
142
|
/** @internal */
|
|
128
|
-
retryOnError?: RetryOnErrorCallbackType<RequestInstance
|
|
143
|
+
retryOnError?: RetryOnErrorCallbackType<RequestInstance> = undefined;
|
|
129
144
|
/** @internal */
|
|
130
|
-
optimistic?: OptimisticCallback<RequestInstance, any
|
|
145
|
+
optimistic?: OptimisticCallback<RequestInstance, any> = undefined;
|
|
131
146
|
|
|
132
147
|
unstable_hasParams: HasParams = false as HasParams;
|
|
133
148
|
unstable_hasPayload: HasPayload = false as HasPayload;
|
|
@@ -204,28 +219,34 @@ export class Request<
|
|
|
204
219
|
this.updatedQueryKey = initialRequestConfiguration?.updatedQueryKey ?? false;
|
|
205
220
|
}
|
|
206
221
|
|
|
222
|
+
/** Set the request headers. Returns a cloned request with the new headers applied. */
|
|
207
223
|
public setHeaders = (headers: HeadersInit) => {
|
|
208
224
|
return this.clone({ headers });
|
|
209
225
|
};
|
|
210
226
|
|
|
227
|
+
/** Set whether authentication interceptors should run for this request. */
|
|
211
228
|
public setAuth = (auth: boolean) => {
|
|
212
229
|
return this.clone({ auth });
|
|
213
230
|
};
|
|
214
231
|
|
|
232
|
+
/** Set the URL path parameters (e.g., `:userId`). */
|
|
215
233
|
public setParams = <P extends ExtractParamsType<this>>(params: P) => {
|
|
216
234
|
return this.clone<HasPayload, P extends null ? false : true, HasQuery>({ params });
|
|
217
235
|
};
|
|
218
236
|
|
|
237
|
+
/** Set the request body payload. */
|
|
219
238
|
public setPayload = <P extends Payload>(payload: P) => {
|
|
220
239
|
return this.clone<P extends null ? false : true, HasParams, HasQuery>({
|
|
221
240
|
payload,
|
|
222
241
|
});
|
|
223
242
|
};
|
|
224
243
|
|
|
244
|
+
/** Set the query parameters appended to the URL. */
|
|
225
245
|
public setQueryParams = (queryParams: QueryParams) => {
|
|
226
246
|
return this.clone<HasPayload, HasParams, true>({ queryParams });
|
|
227
247
|
};
|
|
228
248
|
|
|
249
|
+
/** Set adapter-specific options (e.g., axios config, fetch init). */
|
|
229
250
|
public setOptions = (options: ClientAdapterOptions<Client>) => {
|
|
230
251
|
return this.clone<HasPayload, HasParams, true>({ options });
|
|
231
252
|
};
|
|
@@ -242,14 +263,17 @@ export class Request<
|
|
|
242
263
|
return cloned;
|
|
243
264
|
};
|
|
244
265
|
|
|
266
|
+
/** Set whether in-flight requests with the same abort key are cancelled when a new one is dispatched. */
|
|
245
267
|
public setCancelable = (cancelable: boolean) => {
|
|
246
268
|
return this.clone({ cancelable });
|
|
247
269
|
};
|
|
248
270
|
|
|
271
|
+
/** Set the number of retry attempts on failure. */
|
|
249
272
|
public setRetry = (retry: ClientRequestOptions<Endpoint, Client>["retry"]) => {
|
|
250
273
|
return this.clone({ retry });
|
|
251
274
|
};
|
|
252
275
|
|
|
276
|
+
/** Set the delay in milliseconds between retry attempts. */
|
|
253
277
|
public setRetryTime = (retryTime: ClientRequestOptions<Endpoint, Client>["retryTime"]) => {
|
|
254
278
|
return this.clone({ retryTime });
|
|
255
279
|
};
|
|
@@ -293,53 +317,65 @@ export class Request<
|
|
|
293
317
|
>;
|
|
294
318
|
};
|
|
295
319
|
|
|
320
|
+
/** Set how long (in ms) the response remains in cache before being garbage collected. */
|
|
296
321
|
public setCacheTime = (cacheTime: ClientRequestOptions<Endpoint, Client>["cacheTime"]) => {
|
|
297
322
|
return this.clone({ cacheTime });
|
|
298
323
|
};
|
|
299
324
|
|
|
325
|
+
/** Set whether this request should use the cache. */
|
|
300
326
|
public setCache = (cache: ClientRequestOptions<Endpoint, Client>["cache"]) => {
|
|
301
327
|
return this.clone({ cache });
|
|
302
328
|
};
|
|
303
329
|
|
|
330
|
+
/** Set how long (in ms) cached data is considered fresh before triggering a revalidation. */
|
|
304
331
|
public setStaleTime = (staleTime: ClientRequestOptions<Endpoint, Client>["staleTime"]) => {
|
|
305
332
|
return this.clone({ staleTime });
|
|
306
333
|
};
|
|
307
334
|
|
|
335
|
+
/** Set whether the request should be queued and executed sequentially rather than immediately. */
|
|
308
336
|
public setQueued = (queued: boolean) => {
|
|
309
337
|
return this.clone({ queued });
|
|
310
338
|
};
|
|
311
339
|
|
|
340
|
+
/** Override the abort key used to cancel this request. */
|
|
312
341
|
public setAbortKey = (abortKey: string) => {
|
|
313
342
|
this.updatedAbortKey = true;
|
|
314
343
|
return this.clone({ abortKey });
|
|
315
344
|
};
|
|
316
345
|
|
|
346
|
+
/** Override the cache key used to store/retrieve the response. */
|
|
317
347
|
public setCacheKey = (cacheKey: string) => {
|
|
318
348
|
this.updatedCacheKey = true;
|
|
319
349
|
return this.clone({ cacheKey });
|
|
320
350
|
};
|
|
321
351
|
|
|
352
|
+
/** Override the query key that identifies this request in the dispatcher queue. */
|
|
322
353
|
public setQueryKey = (queryKey: string) => {
|
|
323
354
|
this.updatedQueryKey = true;
|
|
324
355
|
return this.clone({ queryKey });
|
|
325
356
|
};
|
|
326
357
|
|
|
358
|
+
/** Enable or disable request deduplication. When enabled, concurrent identical requests share a single response. */
|
|
327
359
|
public setDeduplicate = (deduplicate: boolean) => {
|
|
328
360
|
return this.clone({ deduplicate });
|
|
329
361
|
};
|
|
330
362
|
|
|
363
|
+
/** Set the time window (in ms) during which identical requests are deduplicated. */
|
|
331
364
|
public setDeduplicateTime = (deduplicateTime: number) => {
|
|
332
365
|
return this.clone({ deduplicateTime });
|
|
333
366
|
};
|
|
334
367
|
|
|
368
|
+
/** Mark the request as used (prevents automatic refetching in hooks). */
|
|
335
369
|
public setUsed = (used: boolean) => {
|
|
336
370
|
return this.clone({ used });
|
|
337
371
|
};
|
|
338
372
|
|
|
373
|
+
/** Set whether the request should be stored in the offline queue when there is no network connection. */
|
|
339
374
|
public setOffline = (offline: boolean) => {
|
|
340
375
|
return this.clone({ offline });
|
|
341
376
|
};
|
|
342
377
|
|
|
378
|
+
/** Attach a mock handler to this request. When mocking is enabled, the handler is called instead of the real adapter. */
|
|
343
379
|
public setMock = (
|
|
344
380
|
fn: (options: {
|
|
345
381
|
request: Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, HasPayload, HasParams, HasQuery>;
|
|
@@ -354,12 +390,14 @@ export class Request<
|
|
|
354
390
|
return this;
|
|
355
391
|
};
|
|
356
392
|
|
|
393
|
+
/** Remove any attached mock handler and disable mocking for this request. */
|
|
357
394
|
public clearMock = () => {
|
|
358
395
|
this.unstable_mock = undefined;
|
|
359
396
|
this.isMockerEnabled = false;
|
|
360
397
|
return this;
|
|
361
398
|
};
|
|
362
399
|
|
|
400
|
+
/** Enable or disable the mocker for this request without removing the mock handler. */
|
|
363
401
|
public setMockingEnabled = (isMockerEnabled: boolean) => {
|
|
364
402
|
this.isMockerEnabled = isMockerEnabled;
|
|
365
403
|
return this;
|
|
@@ -373,7 +411,7 @@ export class Request<
|
|
|
373
411
|
public setPayloadMapper = <MappedPayload extends any | Promise<any>>(
|
|
374
412
|
payloadMapper: (data: Payload) => MappedPayload,
|
|
375
413
|
) => {
|
|
376
|
-
const cloned = this.clone<HasPayload, HasParams, HasQuery>(
|
|
414
|
+
const cloned = this.clone<HasPayload, HasParams, HasQuery>();
|
|
377
415
|
|
|
378
416
|
cloned.unstable_payloadMapper = payloadMapper as typeof this.unstable_payloadMapper;
|
|
379
417
|
|
|
@@ -386,7 +424,7 @@ export class Request<
|
|
|
386
424
|
* @returns new request
|
|
387
425
|
*/
|
|
388
426
|
public setRequestMapper = <NewRequest extends RequestInstance>(requestMapper: RequestMapper<this, NewRequest>) => {
|
|
389
|
-
const cloned = this.clone<HasPayload, HasParams, HasQuery>(
|
|
427
|
+
const cloned = this.clone<HasPayload, HasParams, HasQuery>();
|
|
390
428
|
|
|
391
429
|
cloned.unstable_requestMapper = requestMapper;
|
|
392
430
|
|
|
@@ -425,13 +463,14 @@ export class Request<
|
|
|
425
463
|
let stringEndpoint = String(endpoint);
|
|
426
464
|
if (params) {
|
|
427
465
|
Object.entries(params).forEach(([key, value]) => {
|
|
428
|
-
stringEndpoint = stringEndpoint.
|
|
466
|
+
stringEndpoint = stringEndpoint.replaceAll(new RegExp(`:${key}`, "g"), String(value));
|
|
429
467
|
});
|
|
430
468
|
}
|
|
431
469
|
|
|
432
470
|
return stringEndpoint as Endpoint;
|
|
433
471
|
};
|
|
434
472
|
|
|
473
|
+
/** Serialize the request configuration into a plain JSON object for persistence or transfer. */
|
|
435
474
|
public toJSON(): RequestJSON<this> {
|
|
436
475
|
return {
|
|
437
476
|
requestOptions: this.requestOptions as unknown as RequestOptionsType<
|
|
@@ -473,6 +512,7 @@ export class Request<
|
|
|
473
512
|
};
|
|
474
513
|
}
|
|
475
514
|
|
|
515
|
+
/** Create a new request instance with optional configuration overrides. Used internally by all setter methods. */
|
|
476
516
|
public clone<
|
|
477
517
|
NewData extends true | false = HasPayload,
|
|
478
518
|
NewParams extends true | false = HasParams,
|
|
@@ -537,6 +577,7 @@ export class Request<
|
|
|
537
577
|
return cloned;
|
|
538
578
|
}
|
|
539
579
|
|
|
580
|
+
/** Abort all in-flight requests sharing this request's abort key. */
|
|
540
581
|
public abort = () => {
|
|
541
582
|
const { requestManager } = this.client;
|
|
542
583
|
requestManager.abortByKey(scopeKey(this.abortKey, this.scope));
|
|
@@ -544,6 +585,7 @@ export class Request<
|
|
|
544
585
|
return this.clone();
|
|
545
586
|
};
|
|
546
587
|
|
|
588
|
+
/** Extract the current cache data for this request into a portable hydration payload (useful for SSR). */
|
|
547
589
|
public dehydrate = (config?: {
|
|
548
590
|
/** in case of using adapter without cache we can provide response to dehydrate */
|
|
549
591
|
response?: ResponseType<Response, LocalError | ExtractClientGlobalError<Client>, ExtractClientAdapterType<Client>>;
|
|
@@ -561,7 +603,7 @@ export class Request<
|
|
|
561
603
|
staleTime: this.staleTime,
|
|
562
604
|
cacheKey: this.cacheKey,
|
|
563
605
|
scope: this.scope,
|
|
564
|
-
timestamp:
|
|
606
|
+
timestamp: Date.now(),
|
|
565
607
|
hydrated: true,
|
|
566
608
|
cache: true,
|
|
567
609
|
response,
|
|
@@ -582,7 +624,7 @@ export class Request<
|
|
|
582
624
|
staleTime: this.staleTime,
|
|
583
625
|
cacheKey: this.cacheKey,
|
|
584
626
|
scope: this.scope,
|
|
585
|
-
timestamp:
|
|
627
|
+
timestamp: Date.now(),
|
|
586
628
|
hydrated: true,
|
|
587
629
|
cache: true,
|
|
588
630
|
response: {
|
|
@@ -667,7 +709,7 @@ export class Request<
|
|
|
667
709
|
* ```
|
|
668
710
|
*/
|
|
669
711
|
public send: RequestSendType<this> = async (options?: RequestSendOptionsType<this>) => {
|
|
670
|
-
const { dispatcherType, cachePolicy = "network-only", ...configuration } = options || {};
|
|
712
|
+
const { dispatcherType: _dispatcherType, cachePolicy = "network-only", ...configuration } = options || {};
|
|
671
713
|
|
|
672
714
|
const request = this.clone(configuration) as unknown as this;
|
|
673
715
|
|
|
@@ -698,6 +740,7 @@ export class Request<
|
|
|
698
740
|
return sendRequest(request, sendRequestOptions);
|
|
699
741
|
};
|
|
700
742
|
|
|
743
|
+
/** Reconstruct a Request instance from a previously serialized JSON representation. */
|
|
701
744
|
static fromJSON = <
|
|
702
745
|
NewResponse,
|
|
703
746
|
NewPayload,
|
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import type { RequestResponseType, ResponseSuccessType, ResponseErrorType } from "adapter";
|
|
2
|
+
import type { ClientInstance } from "client";
|
|
3
|
+
import type { RequestEventType, RequestProgressEventType, RequestResponseEventType } from "managers";
|
|
1
4
|
/* eslint-disable @typescript-eslint/no-shadow */
|
|
2
5
|
import type {
|
|
3
6
|
NullableKeys,
|
|
@@ -17,10 +20,8 @@ import type {
|
|
|
17
20
|
ExtractAdapterMethodType,
|
|
18
21
|
TypeWithDefaults,
|
|
19
22
|
} from "types";
|
|
23
|
+
|
|
20
24
|
import type { Request } from "./request";
|
|
21
|
-
import type { RequestResponseType, ResponseSuccessType, ResponseErrorType } from "adapter";
|
|
22
|
-
import type { RequestEventType, RequestProgressEventType, RequestResponseEventType } from "managers";
|
|
23
|
-
import type { ClientInstance } from "client";
|
|
24
25
|
|
|
25
26
|
// Instance
|
|
26
27
|
|
|
@@ -36,6 +37,38 @@ export type RequestInstanceProperties = {
|
|
|
36
37
|
hasPayload?: boolean;
|
|
37
38
|
};
|
|
38
39
|
|
|
40
|
+
/**
|
|
41
|
+
* The **constraint** form of a Request type. Mindset: "any Request that matches this partial shape".
|
|
42
|
+
*
|
|
43
|
+
* Use `RequestInstance` when you are writing a **reusable abstraction** that accepts requests from
|
|
44
|
+
* the outside - generic helpers (`<T extends RequestInstance>`), reusable UI components / hooks,
|
|
45
|
+
* `sdk.$configure({...})` callbacks, mocking utilities, interceptors, return types, etc.
|
|
46
|
+
*
|
|
47
|
+
* Unspecified generic parameters default to `any` **on purpose**: an omitted field means
|
|
48
|
+
* "I do not care about that field, the caller picks anything". This is exactly what you want
|
|
49
|
+
* for a constraint - any concrete `Request` satisfies it. Partial constraints work too:
|
|
50
|
+
* `RequestInstance<{ response: User[] }>` accepts every request that returns `User[]`,
|
|
51
|
+
* regardless of payload, params, queryParams, error, etc.
|
|
52
|
+
*
|
|
53
|
+
* For describing a **single endpoint** inside an SDK schema, use {@link RequestModel} instead.
|
|
54
|
+
* `RequestModel` uses safe non-`any` defaults (`unknown`, `undefined`, `Error`, `string`, `false`)
|
|
55
|
+
* so omitted fields stay strict instead of silently collapsing to `any`.
|
|
56
|
+
*
|
|
57
|
+
* @example
|
|
58
|
+
* ```ts
|
|
59
|
+
* // Reusable component: accepts any request whose response is User[]
|
|
60
|
+
* function UserList<T extends RequestInstance<{ response: User[] }>>(props: { request: T }) {
|
|
61
|
+
* // ...
|
|
62
|
+
* }
|
|
63
|
+
*
|
|
64
|
+
* // sdk.$configure callback: accepts any request the SDK happens to dispatch
|
|
65
|
+
* sdk.$configure({
|
|
66
|
+
* "users.$get": (request: RequestInstance) => request.setMock(() => ({ data: [] })),
|
|
67
|
+
* });
|
|
68
|
+
* ```
|
|
69
|
+
*
|
|
70
|
+
* @see {@link RequestModel} - definition counterpart for SDK schema modeling.
|
|
71
|
+
*/
|
|
39
72
|
export type RequestInstance<
|
|
40
73
|
RequestProperties extends RequestInstanceProperties = {
|
|
41
74
|
response?: any;
|
|
@@ -57,6 +90,75 @@ export type RequestInstance<
|
|
|
57
90
|
any
|
|
58
91
|
>;
|
|
59
92
|
|
|
93
|
+
/**
|
|
94
|
+
* The **definition** form of a Request type. Mindset: "**this** specific endpoint".
|
|
95
|
+
*
|
|
96
|
+
* Use `RequestModel` when you are **defining** a request inside an SDK schema or a request
|
|
97
|
+
* factory. Unlike {@link RequestInstance}, every unspecified field stays strict instead of
|
|
98
|
+
* falling back to `any` - because in a definition, an omitted field means "**there is no
|
|
99
|
+
* payload / no query / no params here**", not "anything goes". The type system will reject
|
|
100
|
+
* mismatches at the call site instead of silently erasing them.
|
|
101
|
+
*
|
|
102
|
+
* The `client` field is also injected automatically by `createSdk(client)` at the SDK boundary,
|
|
103
|
+
* so you never need to repeat it inside schema declarations.
|
|
104
|
+
*
|
|
105
|
+
* ### Defaults for omitted fields
|
|
106
|
+
*
|
|
107
|
+
* | Field | Default | Why |
|
|
108
|
+
* | ----------------- | ---------------- | ---------------------------------------------------------------------- |
|
|
109
|
+
* | `response` | `unknown` | Forces narrowing in consumer code; never silently widened. |
|
|
110
|
+
* | `payload` | `undefined` | "No body declared." `.setData()` is required for typed bodies. |
|
|
111
|
+
* | `queryParams` | `undefined` | Same as payload. |
|
|
112
|
+
* | `error` | `Error` | Sensible default; override per-endpoint when the API has a known shape.|
|
|
113
|
+
* | `endpoint` | `string` | Allows literal narrowing without erasure. Pass a string literal. |
|
|
114
|
+
* | `client` | `ClientInstance` | Injected by `createSdk(client)`; you do not need to set this manually. |
|
|
115
|
+
* | `hasPayload` | `false` | "Caller must call `.setData()`." Override only when payload is bound. |
|
|
116
|
+
* | `hasParams` | `false` | Same as `hasPayload` for params. |
|
|
117
|
+
* | `hasQueryParams` | `false` | Same as `hasPayload` for query params. |
|
|
118
|
+
* | `mutationContext` | `undefined` | Optional context; default is "no context". |
|
|
119
|
+
*
|
|
120
|
+
* @example
|
|
121
|
+
* ```ts
|
|
122
|
+
* // Schema describes shape only - client is injected by createSdk(client).
|
|
123
|
+
* type ApiSchema = {
|
|
124
|
+
* users: {
|
|
125
|
+
* $get: RequestModel<{
|
|
126
|
+
* response: User[];
|
|
127
|
+
* endpoint: "/users";
|
|
128
|
+
* }>;
|
|
129
|
+
* $userId: {
|
|
130
|
+
* $get: RequestModel<{
|
|
131
|
+
* response: User;
|
|
132
|
+
* endpoint: "/users/:userId";
|
|
133
|
+
* }>;
|
|
134
|
+
* };
|
|
135
|
+
* };
|
|
136
|
+
* };
|
|
137
|
+
* ```
|
|
138
|
+
*
|
|
139
|
+
* @see {@link RequestInstance} - constraint counterpart for accepting any Request.
|
|
140
|
+
*/
|
|
141
|
+
export type RequestModel<
|
|
142
|
+
RequestProperties extends RequestInstanceProperties = {
|
|
143
|
+
response?: unknown;
|
|
144
|
+
payload?: undefined;
|
|
145
|
+
queryParams?: undefined;
|
|
146
|
+
error?: Error;
|
|
147
|
+
client?: ClientInstance;
|
|
148
|
+
},
|
|
149
|
+
> = Request<
|
|
150
|
+
TypeWithDefaults<RequestProperties, "response", unknown>,
|
|
151
|
+
TypeWithDefaults<RequestProperties, "payload", undefined>,
|
|
152
|
+
TypeWithDefaults<RequestProperties, "queryParams", undefined>,
|
|
153
|
+
TypeWithDefaults<RequestProperties, "error", Error>,
|
|
154
|
+
TypeWithDefaults<RequestProperties, "endpoint", string>,
|
|
155
|
+
TypeWithDefaults<RequestProperties, "client", ClientInstance>,
|
|
156
|
+
TypeWithDefaults<RequestProperties, "hasPayload", false>,
|
|
157
|
+
TypeWithDefaults<RequestProperties, "hasParams", false>,
|
|
158
|
+
TypeWithDefaults<RequestProperties, "hasQueryParams", false>,
|
|
159
|
+
undefined
|
|
160
|
+
>;
|
|
161
|
+
|
|
60
162
|
// Progress
|
|
61
163
|
export type ProgressEventType = { total: number; loaded: number };
|
|
62
164
|
|
|
@@ -108,7 +210,7 @@ export type RequestJSON<Request extends RequestInstance> = {
|
|
|
108
210
|
*/
|
|
109
211
|
export type RequestOptionsType<GenericEndpoint, AdapterOptions, RequestMethods = HttpMethodsType> = {
|
|
110
212
|
/**
|
|
111
|
-
* Determine the endpoint for
|
|
213
|
+
* Determine the endpoint for the request
|
|
112
214
|
*/
|
|
113
215
|
endpoint: GenericEndpoint;
|
|
114
216
|
/**
|
|
@@ -149,7 +251,7 @@ export type RequestOptionsType<GenericEndpoint, AdapterOptions, RequestMethods =
|
|
|
149
251
|
*/
|
|
150
252
|
staleTime?: number;
|
|
151
253
|
/**
|
|
152
|
-
* Should the requests
|
|
254
|
+
* Should the requests be queued and sent one-by-one
|
|
153
255
|
*/
|
|
154
256
|
queued?: boolean;
|
|
155
257
|
/**
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { getErrorMessage } from "adapter";
|
|
2
|
-
import { HttpMethods } from "constants/http.constants";
|
|
3
2
|
import type { AdapterInstance, ProgressType, RequestResponseType, ResponseType } from "adapter";
|
|
3
|
+
import { SAFE_HTTP_METHODS } from "constants/http.constants";
|
|
4
4
|
import type { Dispatcher } from "dispatcher";
|
|
5
5
|
import type { ExtractAdapterType, ExtractErrorType } from "types";
|
|
6
|
+
|
|
6
7
|
import type {
|
|
7
8
|
OptimisticCallbackResult,
|
|
8
9
|
ProgressEventType,
|
|
@@ -17,18 +18,18 @@ export const scopeKey = (key: string, scope: string | null): string => {
|
|
|
17
18
|
|
|
18
19
|
export const stringifyKey = (value: unknown): string => {
|
|
19
20
|
try {
|
|
20
|
-
if (typeof value === "string") return value;
|
|
21
|
-
if (value === undefined || value === null) return "";
|
|
21
|
+
if (typeof value === "string") {return value;}
|
|
22
|
+
if (value === undefined || value === null) {return "";}
|
|
22
23
|
const data = JSON.stringify(value);
|
|
23
|
-
if (typeof data !== "string") throw new
|
|
24
|
+
if (typeof data !== "string") {throw new TypeError();}
|
|
24
25
|
return data;
|
|
25
|
-
} catch
|
|
26
|
+
} catch {
|
|
26
27
|
return "";
|
|
27
28
|
}
|
|
28
29
|
};
|
|
29
30
|
|
|
30
31
|
export const getProgressValue = ({ loaded, total }: ProgressEventType): number => {
|
|
31
|
-
if (!loaded || !total) return 0;
|
|
32
|
+
if (!loaded || !total) {return 0;}
|
|
32
33
|
return Number(((loaded * 100) / total).toFixed(0));
|
|
33
34
|
};
|
|
34
35
|
|
|
@@ -115,8 +116,8 @@ export const getRequestDispatcher = <Request extends RequestInstance>(
|
|
|
115
116
|
dispatcherType: "auto" | "fetch" | "submit" = "auto",
|
|
116
117
|
): [Dispatcher<ExtractAdapterType<Request>>, isFetchDispatcher: boolean] => {
|
|
117
118
|
const { fetchDispatcher, submitDispatcher } = request.client;
|
|
118
|
-
const
|
|
119
|
-
const isFetchDispatcher = (dispatcherType === "auto" &&
|
|
119
|
+
const isSafeRead = SAFE_HTTP_METHODS.includes(request.method as string);
|
|
120
|
+
const isFetchDispatcher = (dispatcherType === "auto" && isSafeRead) || dispatcherType === "fetch";
|
|
120
121
|
const dispatcher = isFetchDispatcher ? fetchDispatcher : submitDispatcher;
|
|
121
122
|
|
|
122
123
|
return [dispatcher, isFetchDispatcher];
|
|
@@ -152,17 +153,17 @@ export const sendRequest = async <Request extends RequestInstance>(
|
|
|
152
153
|
client: request.client,
|
|
153
154
|
payload: request.payload,
|
|
154
155
|
});
|
|
155
|
-
} catch (
|
|
156
|
+
} catch (error) {
|
|
156
157
|
return {
|
|
157
158
|
data: null,
|
|
158
159
|
error: new Error(
|
|
159
|
-
`Optimistic callback failed: ${
|
|
160
|
+
`Optimistic callback failed: ${error instanceof Error ? error.message : error}`,
|
|
160
161
|
) as unknown as ExtractErrorType<Request>,
|
|
161
162
|
status: null,
|
|
162
163
|
success: false,
|
|
163
164
|
extra: client.adapter.defaultExtra,
|
|
164
|
-
requestTimestamp:
|
|
165
|
-
responseTimestamp:
|
|
165
|
+
requestTimestamp: Date.now(),
|
|
166
|
+
responseTimestamp: Date.now(),
|
|
166
167
|
};
|
|
167
168
|
}
|
|
168
169
|
}
|
|
@@ -214,10 +215,10 @@ export const sendRequest = async <Request extends RequestInstance>(
|
|
|
214
215
|
|
|
215
216
|
const handleResponse = (success: boolean, data: ResponseType<any, any, ExtractAdapterType<Request>>) => {
|
|
216
217
|
// When going offline we can't handle the request as it will be postponed to later resolve
|
|
217
|
-
if (!success && isOfflineStatus) return;
|
|
218
|
+
if (!success && isOfflineStatus) {return;}
|
|
218
219
|
|
|
219
220
|
// When request is in retry mode we need to listen for retries end
|
|
220
|
-
if (!success && willRetry) return;
|
|
221
|
+
if (!success && willRetry) {return;}
|
|
221
222
|
|
|
222
223
|
options?.onResponse?.(enrichedValues);
|
|
223
224
|
$hooks.__emit("onResponse", enrichedValues);
|
|
@@ -257,8 +258,8 @@ export const sendRequest = async <Request extends RequestInstance>(
|
|
|
257
258
|
success: false,
|
|
258
259
|
error: getErrorMessage("deleted") as unknown as ExtractErrorType<Request>,
|
|
259
260
|
extra: request.client.adapter.defaultExtra,
|
|
260
|
-
requestTimestamp:
|
|
261
|
-
responseTimestamp:
|
|
261
|
+
requestTimestamp: Date.now(),
|
|
262
|
+
responseTimestamp: Date.now(),
|
|
262
263
|
});
|
|
263
264
|
|
|
264
265
|
// Unmount Listeners
|