@metamask-previews/base-data-service 1.0.0-preview-8bfa290fb → 2.0.0-preview-0a30e47
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/CHANGELOG.md +10 -8
- package/dist/{BaseDataService.d.mts → BaseDataService.d.ts} +10 -41
- package/dist/BaseDataService.d.ts.map +1 -0
- package/dist/BaseDataService.js +212 -0
- package/dist/BaseDataService.js.map +1 -0
- package/dist/{createServicePolicy.d.mts → createServicePolicy.d.ts} +3 -3
- package/dist/createServicePolicy.d.ts.map +1 -0
- package/dist/{createServicePolicy.mjs → createServicePolicy.js} +3 -3
- package/dist/createServicePolicy.js.map +1 -0
- package/dist/{index.d.cts → index.d.ts} +7 -7
- package/dist/index.d.ts.map +1 -0
- package/dist/{index.mjs → index.js} +4 -4
- package/dist/index.js.map +1 -0
- package/dist/utils.d.ts +13 -0
- package/dist/utils.d.ts.map +1 -0
- package/dist/utils.js +21 -0
- package/dist/utils.js.map +1 -0
- package/package.json +16 -20
- package/dist/BaseDataService.cjs +0 -300
- package/dist/BaseDataService.cjs.map +0 -1
- package/dist/BaseDataService.d.cts +0 -146
- package/dist/BaseDataService.d.cts.map +0 -1
- package/dist/BaseDataService.d.mts.map +0 -1
- package/dist/BaseDataService.mjs +0 -301
- package/dist/BaseDataService.mjs.map +0 -1
- package/dist/createServicePolicy.cjs +0 -228
- package/dist/createServicePolicy.cjs.map +0 -1
- package/dist/createServicePolicy.d.cts +0 -179
- package/dist/createServicePolicy.d.cts.map +0 -1
- package/dist/createServicePolicy.d.mts.map +0 -1
- package/dist/createServicePolicy.mjs.map +0 -1
- package/dist/index.cjs +0 -20
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts.map +0 -1
- package/dist/index.d.mts +0 -7
- package/dist/index.d.mts.map +0 -1
- package/dist/index.mjs.map +0 -1
- package/dist/loggers.cjs +0 -7
- package/dist/loggers.cjs.map +0 -1
- package/dist/loggers.d.cts +0 -5
- package/dist/loggers.d.cts.map +0 -1
- package/dist/loggers.d.mts +0 -5
- package/dist/loggers.d.mts.map +0 -1
- package/dist/loggers.mjs +0 -4
- package/dist/loggers.mjs.map +0 -1
- package/dist/utils.cjs +0 -56
- package/dist/utils.cjs.map +0 -1
- package/dist/utils.d.cts +0 -26
- package/dist/utils.d.cts.map +0 -1
- package/dist/utils.d.mts +0 -26
- package/dist/utils.d.mts.map +0 -1
- package/dist/utils.mjs +0 -51
- package/dist/utils.mjs.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,17 +7,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
- Add `executeMutation` protected method to `BaseDataService` to allow for making server-state-mutating requests ([#9324](https://github.com/MetaMask/core/pull/9324))
|
|
13
|
-
- These kinds of requests are never retried, unlike queries.
|
|
14
|
-
- To use this, create a method in your data service class which takes whatever arguments you need, plus a optional final argument called `globalId`; then call `executeMutation` with a `mutationKey`, `globalId`, and `mutationFn`. See `ExampleDataService` in this package for an example.
|
|
15
|
-
- A `MutationKey` type is also available.
|
|
16
|
-
- The payload for `:cacheUpdated` and `:cacheUpdated:${hash}` events now includes an `objectType` property, which is either "query" or "mutation" ([#9324](https://github.com/MetaMask/core/pull/9324))
|
|
10
|
+
## [2.0.0]
|
|
17
11
|
|
|
18
12
|
### Changed
|
|
19
13
|
|
|
14
|
+
- **BREAKING:** Drop CommonJS support ([#9536](https://github.com/MetaMask/core/pull/9536))
|
|
15
|
+
- This package is now ESM-only, but can still be used in CommonJS projects via `require(esm)` in modern Node.js versions (22+), or dynamic imports in older Node.js versions.
|
|
16
|
+
- **BREAKING:** Bump minimum Node.js version to 22 ([#9976](https://github.com/MetaMask/core/pull/9976))
|
|
17
|
+
- **BREAKING:** Bump TypeScript target to ES2022 ([#10019](https://github.com/MetaMask/core/pull/10019))
|
|
18
|
+
- This package now ships ES2022 code, requiring a compatible modern environment or bundler configuration to consume.
|
|
20
19
|
- Bump `@metamask/utils` from `^11.11.0` to `^11.12.0` ([#10076](https://github.com/MetaMask/core/pull/10076))
|
|
20
|
+
- Bump `@metamask/messenger` from `^2.0.0` to `^3.0.0` ([#10160](https://github.com/MetaMask/core/pull/10160))
|
|
21
|
+
- Bump `@metamask/storage-service` from `^1.0.2` to `^2.0.0` ([#10160](https://github.com/MetaMask/core/pull/10160))
|
|
21
22
|
|
|
22
23
|
### Fixed
|
|
23
24
|
|
|
@@ -95,7 +96,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
95
96
|
|
|
96
97
|
- Initial release ([#8039](https://github.com/MetaMask/core/pull/8039), [#8292](https://github.com/MetaMask/core/pull/8292))
|
|
97
98
|
|
|
98
|
-
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/base-data-service@
|
|
99
|
+
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/base-data-service@2.0.0...HEAD
|
|
100
|
+
[2.0.0]: https://github.com/MetaMask/core/compare/@metamask/base-data-service@1.0.0...@metamask/base-data-service@2.0.0
|
|
99
101
|
[1.0.0]: https://github.com/MetaMask/core/compare/@metamask/base-data-service@0.1.3...@metamask/base-data-service@1.0.0
|
|
100
102
|
[0.1.3]: https://github.com/MetaMask/core/compare/@metamask/base-data-service@0.1.2...@metamask/base-data-service@0.1.3
|
|
101
103
|
[0.1.2]: https://github.com/MetaMask/core/compare/@metamask/base-data-service@0.1.1...@metamask/base-data-service@0.1.2
|
|
@@ -1,16 +1,10 @@
|
|
|
1
|
-
import { Messenger, ActionConstraint, EventConstraint, MessengerActions, MessengerEvents } from
|
|
2
|
-
import type { StorageServiceGetItemAction, StorageServiceRemoveItemAction, StorageServiceSetItemAction } from
|
|
3
|
-
import { Struct } from
|
|
4
|
-
import type { Json } from
|
|
5
|
-
import { DefaultError, DehydratedState, FetchQueryOptions, InfiniteData, InfiniteQueryPageParamsOptions, InvalidateOptions, InvalidateQueryFilters,
|
|
6
|
-
import { CreateServicePolicyOptions } from
|
|
7
|
-
|
|
8
|
-
* Data service mutations and queries use the following format:
|
|
9
|
-
* `['${ServiceName}:${ActionName}', ...params]`
|
|
10
|
-
*/
|
|
11
|
-
type Key = [string, ...Json[]] | readonly [string, ...Json[]];
|
|
12
|
-
export type QueryKey = Key;
|
|
13
|
-
export type MutationKey = Key;
|
|
1
|
+
import { Messenger, ActionConstraint, EventConstraint, MessengerActions, MessengerEvents } from '@metamask/messenger';
|
|
2
|
+
import type { StorageServiceGetItemAction, StorageServiceRemoveItemAction, StorageServiceSetItemAction } from '@metamask/storage-service';
|
|
3
|
+
import { Struct } from '@metamask/superstruct';
|
|
4
|
+
import type { Json } from '@metamask/utils';
|
|
5
|
+
import { DefaultError, DehydratedState, FetchQueryOptions, InfiniteData, InfiniteQueryPageParamsOptions, InvalidateOptions, InvalidateQueryFilters, OmitKeyof, QueryClientConfig, QueryFunction, WithRequired } from '@tanstack/query-core';
|
|
6
|
+
import { CreateServicePolicyOptions } from './createServicePolicy.js';
|
|
7
|
+
export type QueryKey = [string, ...Json[]] | readonly [string, ...Json[]];
|
|
14
8
|
/**
|
|
15
9
|
* The supertype of all messengers, scoped to a namespace.
|
|
16
10
|
*
|
|
@@ -19,14 +13,12 @@ export type MutationKey = Key;
|
|
|
19
13
|
*/
|
|
20
14
|
export type BaseMessenger<Namespace extends string> = Messenger<Namespace, ActionConstraint, EventConstraint, any>;
|
|
21
15
|
export type DataServiceGranularCacheUpdatedPayload = {
|
|
22
|
-
objectType: 'query' | 'mutation';
|
|
23
|
-
} & ({
|
|
24
16
|
type: 'added' | 'updated';
|
|
25
17
|
state: DehydratedState;
|
|
26
18
|
} | {
|
|
27
19
|
type: 'removed';
|
|
28
20
|
state: null;
|
|
29
|
-
}
|
|
21
|
+
};
|
|
30
22
|
export type DataServiceCacheUpdatedPayload = DataServiceGranularCacheUpdatedPayload & {
|
|
31
23
|
hash: string;
|
|
32
24
|
};
|
|
@@ -81,11 +73,10 @@ export declare class BaseDataService<ServiceName extends string, ServiceMessenge
|
|
|
81
73
|
*
|
|
82
74
|
* @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.
|
|
83
75
|
* Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
|
|
84
|
-
* @param options.queryFn - The query function.
|
|
85
76
|
* @param options.responseStruct - An optional struct for validating the response of the query function.
|
|
86
77
|
* @returns The query results.
|
|
87
78
|
*/
|
|
88
|
-
protected fetchQuery<TQueryFnData extends Json, TError = DefaultError, TDataStruct extends Struct<TQueryFnData> | undefined = undefined, TData = TDataStruct extends Struct<infer StructType> ? StructType : TQueryFnData, TQueryKey extends QueryKey = QueryKey>({
|
|
79
|
+
protected fetchQuery<TQueryFnData extends Json, TError = DefaultError, TDataStruct extends Struct<TQueryFnData> | undefined = undefined, TData = TDataStruct extends Struct<infer StructType> ? StructType : TQueryFnData, TQueryKey extends QueryKey = QueryKey>({ responseStruct, ...options }: WithRequired<OmitKeyof<FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>, 'retry' | 'retryDelay' | 'queryFn'>, 'queryKey'> & {
|
|
89
80
|
queryFn: QueryFunction<TQueryFnData, TQueryKey>;
|
|
90
81
|
responseStruct?: TDataStruct;
|
|
91
82
|
}): Promise<TData>;
|
|
@@ -102,28 +93,6 @@ export declare class BaseDataService<ServiceName extends string, ServiceMessenge
|
|
|
102
93
|
queryFn: QueryFunction<TQueryFnData, TQueryKey, TPageParam>;
|
|
103
94
|
responseStruct?: TDataStruct;
|
|
104
95
|
}, pageParam?: TPageParam): Promise<TData>;
|
|
105
|
-
/**
|
|
106
|
-
* Execute a mutation (e.g. a request that is expected to change server-side data).
|
|
107
|
-
* Unlike `fetchQuery`, the request will not be cached or retried.
|
|
108
|
-
*
|
|
109
|
-
* @param options - The options defining the mutation. Keep in mind that `mutationKey` and `mutationFn` are required when using data services.
|
|
110
|
-
* Additionally, `retry` and `retryDelay` are not available.
|
|
111
|
-
* @param options.mutationFn - The mutation function.
|
|
112
|
-
* @param options.responseStruct - An optional struct for validating the response of the mutation function.
|
|
113
|
-
* @param options.globalId - A string which uniquely identifies this mutation
|
|
114
|
-
* across different query clients — specifically, the one in this data service
|
|
115
|
-
* and the one that `createUIQueryClient` in `@metamask/react-data-query`
|
|
116
|
-
* holds (in fact usually you don't need to pass this — `createUIQueryClient`
|
|
117
|
-
* will do it automatically). This global ID will be stored in the new
|
|
118
|
-
* mutation `meta` data and included in `:cacheUpdated` payloads.
|
|
119
|
-
* @returns The mutation results.
|
|
120
|
-
*/
|
|
121
|
-
protected executeMutation<TMutationFnData extends Json, TDataStruct extends Struct<any> | undefined = undefined, TData = TDataStruct extends Struct<infer StructType> ? StructType : TMutationFnData, TError = DefaultError, TOnMutateResult = unknown, TMutationKey extends MutationKey = MutationKey>({ mutationFn, responseStruct, globalId, ...options }: OmitKeyof<MutationOptions<TData, TError, Record<never, never>, TOnMutateResult>, 'retry' | 'retryDelay' | 'mutationKey' | 'mutationFn'> & {
|
|
122
|
-
mutationKey: TMutationKey;
|
|
123
|
-
mutationFn: MutationFunction<TMutationFnData, Record<never, never>>;
|
|
124
|
-
responseStruct?: TDataStruct;
|
|
125
|
-
globalId?: string;
|
|
126
|
-
}): Promise<TData>;
|
|
127
96
|
/**
|
|
128
97
|
* Invalidate queries serviced by this data service.
|
|
129
98
|
*
|
|
@@ -143,4 +112,4 @@ export declare class BaseDataService<ServiceName extends string, ServiceMessenge
|
|
|
143
112
|
destroy(): void;
|
|
144
113
|
}
|
|
145
114
|
export {};
|
|
146
|
-
//# sourceMappingURL=BaseDataService.d.
|
|
115
|
+
//# sourceMappingURL=BaseDataService.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"BaseDataService.d.ts","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,gBAAgB,EAChB,eAAe,EACf,gBAA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,QAAQ,EACrC,UAAU,SAAS,IAAI,GAAG,IAAI,EAE9B,EACE,cAAc,EACd,GAAG,OAAO,EACX,EAAE,YAAY,CACb,SAAS,CACP,iBAAiB,CACf,YAAY,EACZ,MAAM,EACN,YAAY,CAAC,KAAK,EAAE,UAAU,CAAC,EAC/B,SAAS,EACT,UAAU,CACX,EACD,OAAO,GAAG,YAAY,GAAG,SAAS,GAAG,kBAAkB,CACxD,EACD,UAAU,CACX,GACC,8BAA8B,CAAC,YAAY,EAAE,UAAU,CAAC,GAAG;QACzD,OAAO,EAAE,aAAa,CAAC,YAAY,EAAE,SAAS,EAAE,UAAU,CAAC,CAAC;QAC5D,cAAc,CAAC,EAAE,WAAW,CAAC;KAC9B,EACH,SAAS,CAAC,EAAE,UAAU,GACrB,OAAO,CAAC,KAAK,CAAC,CAqDhB;IAED;;;;;;OAMG;IACG,iBAAiB,CACrB,OAAO,CAAC,EAAE,sBAAsB,CAAC,QAAQ,CAAC,EAC1C,OAAO,CAAC,EAAE,iBAAiB,GAC1B,OAAO,CAAC,IAAI,CAAC,CAEf;IAED;;OAEG;IACH,IAAI,IAAI,IAAI,CAKX;IAED;;;OAGG;IACH,OAAO,IAAI,IAAI,CAMd;CAqGF"}
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import { Duration, inMilliseconds } from '@metamask/utils';
|
|
2
|
+
import { QueryClient, dehydrate, hydrate, } from '@tanstack/query-core';
|
|
3
|
+
import deepEqual from 'fast-deep-equal';
|
|
4
|
+
import { debounce } from 'lodash-es';
|
|
5
|
+
import { createServicePolicy, } from './createServicePolicy.js';
|
|
6
|
+
import { processQueryResponse } from './utils.js';
|
|
7
|
+
// Defaults to apply to all data service queries if no default option specified
|
|
8
|
+
const QUERY_CLIENT_DEFAULTS = {
|
|
9
|
+
queries: {
|
|
10
|
+
retry: false,
|
|
11
|
+
staleTime: inMilliseconds(1, Duration.Minute),
|
|
12
|
+
},
|
|
13
|
+
};
|
|
14
|
+
export const STORAGE_SERVICE_KEY = 'cache';
|
|
15
|
+
export class BaseDataService {
|
|
16
|
+
name;
|
|
17
|
+
#messenger;
|
|
18
|
+
#externalMessenger;
|
|
19
|
+
messenger;
|
|
20
|
+
#policy;
|
|
21
|
+
#queryClient;
|
|
22
|
+
#queryCacheUnsubscribe;
|
|
23
|
+
#debouncedPersist;
|
|
24
|
+
#persistenceConfig;
|
|
25
|
+
constructor({ name, messenger, queryClientConfig = {}, policyOptions, persistenceConfig, }) {
|
|
26
|
+
this.name = name;
|
|
27
|
+
// We store two narrowly-typed messengers alongside the generic public one:
|
|
28
|
+
// - #messenger handles the service's own action registration and event publishing
|
|
29
|
+
// - #externalMessenger handles calls to external actions
|
|
30
|
+
// Splitting them avoids TypeScript issues with mixing template-literals with regular strings
|
|
31
|
+
this.#messenger = messenger;
|
|
32
|
+
this.#externalMessenger = messenger;
|
|
33
|
+
this.messenger = messenger;
|
|
34
|
+
this.#queryClient = new QueryClient({
|
|
35
|
+
...queryClientConfig,
|
|
36
|
+
defaultOptions: {
|
|
37
|
+
queries: {
|
|
38
|
+
...QUERY_CLIENT_DEFAULTS.queries,
|
|
39
|
+
...queryClientConfig.defaultOptions?.queries,
|
|
40
|
+
},
|
|
41
|
+
mutations: queryClientConfig.defaultOptions?.mutations,
|
|
42
|
+
},
|
|
43
|
+
});
|
|
44
|
+
this.#persistenceConfig = persistenceConfig;
|
|
45
|
+
this.#policy = createServicePolicy(policyOptions);
|
|
46
|
+
this.#debouncedPersist =
|
|
47
|
+
this.#persistenceConfig &&
|
|
48
|
+
debounce(() => {
|
|
49
|
+
this.#persistCache().catch(
|
|
50
|
+
/* istanbul ignore next */
|
|
51
|
+
(error) => this.#messenger.captureException?.(error));
|
|
52
|
+
}, this.#persistenceConfig.writeDelay ??
|
|
53
|
+
inMilliseconds(10, Duration.Second), {
|
|
54
|
+
maxWait: this.#persistenceConfig.maxWriteDelay ??
|
|
55
|
+
inMilliseconds(1, Duration.Minute),
|
|
56
|
+
});
|
|
57
|
+
this.#queryCacheUnsubscribe = this.#queryClient
|
|
58
|
+
.getQueryCache()
|
|
59
|
+
.subscribe((event) => {
|
|
60
|
+
if (['added', 'updated', 'removed'].includes(event.type)) {
|
|
61
|
+
this.#publishCacheUpdate(event.query.queryHash, event.type);
|
|
62
|
+
this.#debouncedPersist?.();
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
this.#messenger.registerActionHandler(`${this.name}:invalidateQueries`, this.invalidateQueries.bind(this));
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Fetch a query.
|
|
69
|
+
*
|
|
70
|
+
* @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.
|
|
71
|
+
* Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
|
|
72
|
+
* @param options.responseStruct - An optional struct for validating the response of the query function.
|
|
73
|
+
* @returns The query results.
|
|
74
|
+
*/
|
|
75
|
+
async fetchQuery({ responseStruct, ...options }) {
|
|
76
|
+
return this.#queryClient.fetchQuery({
|
|
77
|
+
...options,
|
|
78
|
+
queryFn: async (context) => {
|
|
79
|
+
const response = await this.#policy.execute(() => options.queryFn(context));
|
|
80
|
+
return processQueryResponse(options.queryKey, response, responseStruct);
|
|
81
|
+
},
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Fetch a paginated query.
|
|
86
|
+
*
|
|
87
|
+
* @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.
|
|
88
|
+
* Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
|
|
89
|
+
* @param options.responseStruct - An optional struct for validating the response of the query function.
|
|
90
|
+
* @param pageParam - An optional page parameter.
|
|
91
|
+
* @returns The query result, exclusively the requested page is returned.
|
|
92
|
+
*/
|
|
93
|
+
async fetchInfiniteQuery({ responseStruct, ...options }, pageParam) {
|
|
94
|
+
const cache = this.#queryClient.getQueryCache();
|
|
95
|
+
const query = cache.find({
|
|
96
|
+
queryKey: options.queryKey,
|
|
97
|
+
});
|
|
98
|
+
if (!query?.state.data || !pageParam) {
|
|
99
|
+
const result = await this.#queryClient.fetchInfiniteQuery({
|
|
100
|
+
...options,
|
|
101
|
+
initialPageParam: pageParam ?? options.initialPageParam,
|
|
102
|
+
queryFn: async (context) => {
|
|
103
|
+
const response = await this.#policy.execute(async () => options.queryFn({
|
|
104
|
+
...context,
|
|
105
|
+
pageParam: context.meta?.pageParam ?? context.pageParam,
|
|
106
|
+
}));
|
|
107
|
+
return processQueryResponse(options.queryKey, response, responseStruct);
|
|
108
|
+
},
|
|
109
|
+
});
|
|
110
|
+
return result.pages[0];
|
|
111
|
+
}
|
|
112
|
+
const { pages, pageParams } = query.state.data;
|
|
113
|
+
const next = options.getNextPageParam(pages[pages.length - 1], pages, pageParams[pageParams.length - 1], pageParams);
|
|
114
|
+
const direction = deepEqual(pageParam, next) ? 'forward' : 'backward';
|
|
115
|
+
const result = await query.fetch({ ...query.options, meta: { pageParam } }, { meta: { fetchMore: { direction } } });
|
|
116
|
+
const pageIndex = result.pageParams.findIndex((param) => deepEqual(param, pageParam));
|
|
117
|
+
return result.pages[pageIndex];
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Invalidate queries serviced by this data service.
|
|
121
|
+
*
|
|
122
|
+
* @param filters - Optional filter for selecting specific queries.
|
|
123
|
+
* @param options - Additional optional options for query invalidations.
|
|
124
|
+
* @returns Nothing.
|
|
125
|
+
*/
|
|
126
|
+
async invalidateQueries(filters, options) {
|
|
127
|
+
return this.#queryClient.invalidateQueries(filters, options);
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Initialize the service, rehydrating the cache with persisted data if possible.
|
|
131
|
+
*/
|
|
132
|
+
init() {
|
|
133
|
+
this.#loadCache().catch(
|
|
134
|
+
/* istanbul ignore next */
|
|
135
|
+
(error) => this.#messenger.captureException?.(error));
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Prepares the service for garbage collection. This should be extended
|
|
139
|
+
* by any subclasses to clean up any additional connections or events.
|
|
140
|
+
*/
|
|
141
|
+
destroy() {
|
|
142
|
+
this.#debouncedPersist?.cancel();
|
|
143
|
+
this.#queryCacheUnsubscribe();
|
|
144
|
+
this.#queryClient.clear();
|
|
145
|
+
this.messenger.clearSubscriptions();
|
|
146
|
+
this.messenger.clearActions();
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Publish `cacheUpdated` events when a given query changes.
|
|
150
|
+
*
|
|
151
|
+
* @param hash The hash of the query.
|
|
152
|
+
* @param type The type of cache update.
|
|
153
|
+
*/
|
|
154
|
+
#publishCacheUpdate(hash, type) {
|
|
155
|
+
const state = type === 'added' || type === 'updated'
|
|
156
|
+
? dehydrate(this.#queryClient, {
|
|
157
|
+
shouldDehydrateQuery: (query) => query.queryHash === hash,
|
|
158
|
+
})
|
|
159
|
+
: null;
|
|
160
|
+
this.#messenger.publish(`${this.name}:cacheUpdated`, {
|
|
161
|
+
type,
|
|
162
|
+
hash,
|
|
163
|
+
state,
|
|
164
|
+
});
|
|
165
|
+
this.#messenger.publish(`${this.name}:cacheUpdated:${hash}`, {
|
|
166
|
+
type,
|
|
167
|
+
state,
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Persist the query client cache using the StorageService, if the cache is not empty.
|
|
172
|
+
*
|
|
173
|
+
* @returns Nothing.
|
|
174
|
+
*/
|
|
175
|
+
async #persistCache() {
|
|
176
|
+
const state = dehydrate(this.#queryClient, {
|
|
177
|
+
// This is the default, but we specify it to be explicit.
|
|
178
|
+
shouldDehydrateQuery: (query) => query.state.status === 'success',
|
|
179
|
+
});
|
|
180
|
+
if (state.queries.length === 0 && state.mutations.length === 0) {
|
|
181
|
+
await this.#externalMessenger.call('StorageService:removeItem', this.name, STORAGE_SERVICE_KEY);
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
const cache = {
|
|
185
|
+
timestamp: Date.now(),
|
|
186
|
+
state,
|
|
187
|
+
};
|
|
188
|
+
await this.#externalMessenger.call('StorageService:setItem', this.name, STORAGE_SERVICE_KEY, cache);
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Load the query client cache from the StorageService, if persistence is configured
|
|
192
|
+
* and the persisted cache is not expired.
|
|
193
|
+
*
|
|
194
|
+
* @returns Nothing.
|
|
195
|
+
*/
|
|
196
|
+
async #loadCache() {
|
|
197
|
+
if (!this.#persistenceConfig) {
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
const { result: untypedCache } = await this.#externalMessenger.call('StorageService:getItem', this.name, STORAGE_SERVICE_KEY);
|
|
201
|
+
if (!untypedCache) {
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
const cache = untypedCache;
|
|
205
|
+
if (Date.now() - cache.timestamp >= this.#persistenceConfig.maxAge) {
|
|
206
|
+
await this.#externalMessenger.call('StorageService:removeItem', this.name, STORAGE_SERVICE_KEY);
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
hydrate(this.#queryClient, cache.state);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
//# sourceMappingURL=BaseDataService.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"BaseDataService.js","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAE3D,OAAO,EAUL,WAAW,EAIX,SAAS,EACT,OAAO,GACR,MAAM,sBAAsB,CAAC;AAC9B,OAAO,SAAS,MAAM,iBAAiB,CAAC;AACxC,OAAO,EAAE,QAAQ,EAAiB,MAAM,WAAW,CAAC;AAEpD,OAAO,EACL,mBAAmB,GAGpB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;AAiElD,+EAA+E;AAC/E,MAAM,qBAAqB,GAAmB;IAC5C,OAAO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wBAAwB,EACxB,IAAI,CAAC,IAAI,EACT,mBAAmB,EACnB,KAAwB,CACzB,CAAC;IACJ,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,UAAU;QACd,IAAI,CAAC,IAAI,CAAC,kBAAkB,EAAE,CAAC;YAC7B,OAAO;QACT,CAAC;QAED,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,GAAG,MAAM,IAAI,CAAC,kBAAkB,CAAC,IAAI,CACjE,wBAAwB,EACxB,IAAI,CAAC,IAAI,EACT,mBAAmB,CACpB,CAAC;QAEF,IAAI,CAAC,YAAY,EAAE,CAAC;YAClB,OAAO;QACT,CAAC;QAED,MAAM,KAAK,GAAG,YAAyC,CAAC;QAExD,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,SAAS,IAAI,IAAI,CAAC,kBAAkB,CAAC,MAAM,EAAE,CAAC;YACnE,MAAM,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAChC,2BAA2B,EAC3B,IAAI,CAAC,IAAI,EACT,mBAAmB,CACpB,CAAC;YACF,OAAO;QACT,CAAC;QAED,OAAO,CAAC,IAAI,CAAC,YAAY,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;IAC1C,CAAC;CACF","sourcesContent":["import {\n Messenger,\n ActionConstraint,\n EventConstraint,\n MessengerActions,\n MessengerEvents,\n} from '@metamask/messenger';\nimport type {\n StorageServiceGetItemAction,\n StorageServiceRemoveItemAction,\n StorageServiceSetItemAction,\n} from '@metamask/storage-service';\nimport { Struct } from '@metamask/superstruct';\nimport { Duration, inMilliseconds } from '@metamask/utils';\nimport type { Json } from '@metamask/utils';\nimport {\n DefaultError,\n DefaultOptions,\n DehydratedState,\n FetchQueryOptions,\n InfiniteData,\n InfiniteQueryPageParamsOptions,\n InvalidateOptions,\n InvalidateQueryFilters,\n OmitKeyof,\n QueryClient,\n QueryClientConfig,\n QueryFunction,\n WithRequired,\n dehydrate,\n hydrate,\n} from '@tanstack/query-core';\nimport deepEqual from 'fast-deep-equal';\nimport { debounce, DebouncedFunc } from 'lodash-es';\n\nimport {\n createServicePolicy,\n CreateServicePolicyOptions,\n ServicePolicy,\n} from './createServicePolicy.js';\nimport { processQueryResponse } from './utils.js';\n\n// Data service queries use the following format: ['ServiceActionName', ...params]\nexport type QueryKey = [string, ...Json[]] | readonly [string, ...Json[]];\n\n/**\n * The supertype of all messengers, scoped to a namespace.\n *\n * @template Namespace - The namespace for the messenger's own actions and\n * events.\n */\nexport type BaseMessenger<Namespace extends string> = Messenger<\n Namespace,\n ActionConstraint,\n EventConstraint,\n // Use `any` to allow any parent to be set. `any` is harmless in a type constraint anyway,\n // it's the one totally safe place to use it.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any\n>;\n\nexport type DataServiceGranularCacheUpdatedPayload =\n | { type: 'added' | 'updated'; state: DehydratedState }\n | {\n type: 'removed';\n state: null;\n };\n\nexport type DataServiceCacheUpdatedPayload =\n DataServiceGranularCacheUpdatedPayload & {\n hash: string;\n };\n\ntype CacheUpdatedType = DataServiceCacheUpdatedPayload['type'];\n\nexport type DataServiceInvalidateQueriesAction<ServiceName extends string> = {\n type: `${ServiceName}:invalidateQueries`;\n handler: BaseDataService<\n ServiceName,\n BaseMessenger<ServiceName>\n >['invalidateQueries'];\n};\n\nexport type DataServiceActions<ServiceName extends string> =\n DataServiceInvalidateQueriesAction<ServiceName>;\n\ntype DataServiceAllowedActions =\n | StorageServiceGetItemAction\n | StorageServiceSetItemAction\n | StorageServiceRemoveItemAction;\n\nexport type DataServiceCacheUpdatedEvent<ServiceName extends string> = {\n type: `${ServiceName}:cacheUpdated`;\n payload: [DataServiceCacheUpdatedPayload];\n};\n\nexport type DataServiceGranularCacheUpdatedEvent<ServiceName extends string> = {\n type: `${ServiceName}:cacheUpdated:${string}`;\n payload: [DataServiceGranularCacheUpdatedPayload];\n};\n\nexport type DataServiceEvents<ServiceName extends string> =\n | DataServiceCacheUpdatedEvent<ServiceName>\n | DataServiceGranularCacheUpdatedEvent<ServiceName>;\n\n// Defaults to apply to all data service queries if no default option specified\nconst QUERY_CLIENT_DEFAULTS: DefaultOptions = {\n queries: {\n retry: false,\n staleTime: inMilliseconds(1, Duration.Minute),\n },\n};\n\nexport const STORAGE_SERVICE_KEY = 'cache';\n\n/**\n * Options for persistence configuration.\n */\nexport type PersistenceConfiguration = {\n /**\n * The maximum age before the cache is treated as expired in milliseconds.\n * This is relevant for rehydrating the state during initialization,\n * if the cached state is too old it will be discarded.\n */\n maxAge: number;\n /**\n * The number of milliseconds to wait before triggering persistence following a cache update.\n */\n writeDelay?: number;\n /**\n * The maximum number of milliseconds to wait between persistence writes.\n */\n maxWriteDelay?: number;\n};\n\ntype PersistedCache = {\n state: DehydratedState;\n timestamp: number;\n};\n\nexport class BaseDataService<\n ServiceName extends string,\n ServiceMessenger extends BaseMessenger<ServiceName>,\n> {\n public readonly name: ServiceName;\n\n readonly #messenger: Messenger<\n ServiceName,\n DataServiceActions<ServiceName>,\n DataServiceEvents<ServiceName>\n >;\n\n readonly #externalMessenger: Messenger<\n ServiceName,\n DataServiceAllowedActions\n >;\n\n protected messenger: ServiceMessenger;\n\n readonly #policy: ServicePolicy;\n\n readonly #queryClient: QueryClient;\n\n readonly #queryCacheUnsubscribe: () => void;\n\n readonly #debouncedPersist?: DebouncedFunc<() => void>;\n\n readonly #persistenceConfig?: PersistenceConfiguration;\n\n constructor({\n name,\n messenger,\n queryClientConfig = {},\n policyOptions,\n persistenceConfig,\n }: {\n name: ServiceName;\n messenger: DataServiceActions<ServiceName>['type'] extends\n | MessengerActions<ServiceMessenger>['type']\n | DataServiceAllowedActions['type']\n ? DataServiceEvents<ServiceName>['type'] extends MessengerEvents<ServiceMessenger>['type']\n ? ServiceMessenger\n : never\n : never;\n queryClientConfig?: QueryClientConfig;\n policyOptions?: CreateServicePolicyOptions;\n persistenceConfig?: PersistenceConfiguration;\n }) {\n this.name = name;\n\n // We store two narrowly-typed messengers alongside the generic public one:\n // - #messenger handles the service's own action registration and event publishing\n // - #externalMessenger handles calls to external actions\n // Splitting them avoids TypeScript issues with mixing template-literals with regular strings\n this.#messenger = messenger as unknown as Messenger<\n ServiceName,\n DataServiceActions<ServiceName>,\n DataServiceEvents<ServiceName>\n >;\n this.#externalMessenger = messenger as unknown as Messenger<\n ServiceName,\n DataServiceAllowedActions\n >;\n this.messenger = messenger;\n\n this.#queryClient = new QueryClient({\n ...queryClientConfig,\n defaultOptions: {\n queries: {\n ...QUERY_CLIENT_DEFAULTS.queries,\n ...queryClientConfig.defaultOptions?.queries,\n },\n mutations: queryClientConfig.defaultOptions?.mutations,\n },\n });\n\n this.#persistenceConfig = persistenceConfig;\n\n this.#policy = createServicePolicy(policyOptions);\n\n this.#debouncedPersist =\n this.#persistenceConfig &&\n debounce(\n () => {\n this.#persistCache().catch(\n /* istanbul ignore next */\n (error) => this.#messenger.captureException?.(error),\n );\n },\n this.#persistenceConfig.writeDelay ??\n inMilliseconds(10, Duration.Second),\n {\n maxWait:\n this.#persistenceConfig.maxWriteDelay ??\n inMilliseconds(1, Duration.Minute),\n },\n );\n\n this.#queryCacheUnsubscribe = this.#queryClient\n .getQueryCache()\n .subscribe((event) => {\n if (['added', 'updated', 'removed'].includes(event.type)) {\n this.#publishCacheUpdate(\n event.query.queryHash,\n event.type as CacheUpdatedType,\n );\n\n this.#debouncedPersist?.();\n }\n });\n\n this.#messenger.registerActionHandler(\n `${this.name}:invalidateQueries`,\n this.invalidateQueries.bind(this),\n );\n }\n\n /**\n * Fetch a query.\n *\n * @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.\n * Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.\n * @param options.responseStruct - An optional struct for validating the response of the query function.\n * @returns The query results.\n */\n protected async fetchQuery<\n TQueryFnData extends Json,\n TError = DefaultError,\n TDataStruct extends Struct<TQueryFnData> | undefined = undefined,\n TData = TDataStruct extends Struct<infer StructType>\n ? StructType\n : TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n >({\n responseStruct,\n ...options\n }: WithRequired<\n OmitKeyof<\n FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'retry' | 'retryDelay' | 'queryFn'\n >,\n 'queryKey'\n > & {\n queryFn: QueryFunction<TQueryFnData, TQueryKey>;\n responseStruct?: TDataStruct;\n }): Promise<TData> {\n return this.#queryClient.fetchQuery({\n ...options,\n queryFn: async (context) => {\n const response = await this.#policy.execute(() =>\n options.queryFn(context),\n );\n return processQueryResponse(options.queryKey, response, responseStruct);\n },\n });\n }\n\n /**\n * Fetch a paginated query.\n *\n * @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.\n * Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.\n * @param options.responseStruct - An optional struct for validating the response of the query function.\n * @param pageParam - An optional page parameter.\n * @returns The query result, exclusively the requested page is returned.\n */\n protected async fetchInfiniteQuery<\n TQueryFnData extends Json,\n TError = DefaultError,\n TDataStruct extends Struct<TQueryFnData> | undefined = undefined,\n TData extends TQueryFnData = TDataStruct extends Struct<infer StructType>\n ? StructType\n : TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam extends Json = Json,\n >(\n {\n responseStruct,\n ...options\n }: WithRequired<\n OmitKeyof<\n FetchQueryOptions<\n TQueryFnData,\n TError,\n InfiniteData<TData, TPageParam>,\n TQueryKey,\n TPageParam\n >,\n 'retry' | 'retryDelay' | 'queryFn' | 'initialPageParam'\n >,\n 'queryKey'\n > &\n InfiniteQueryPageParamsOptions<TQueryFnData, TPageParam> & {\n queryFn: QueryFunction<TQueryFnData, TQueryKey, TPageParam>;\n responseStruct?: TDataStruct;\n },\n pageParam?: TPageParam,\n ): Promise<TData> {\n const cache = this.#queryClient.getQueryCache();\n\n const query = cache.find<\n TQueryFnData,\n TError,\n InfiniteData<TData, TPageParam>\n >({\n queryKey: options.queryKey,\n });\n\n if (!query?.state.data || !pageParam) {\n const result = await this.#queryClient.fetchInfiniteQuery({\n ...options,\n initialPageParam: pageParam ?? options.initialPageParam,\n queryFn: async (context) => {\n const response = await this.#policy.execute(async () =>\n options.queryFn({\n ...context,\n pageParam: context.meta?.pageParam ?? context.pageParam,\n }),\n );\n return processQueryResponse(\n options.queryKey,\n response,\n responseStruct,\n );\n },\n });\n\n return result.pages[0];\n }\n\n const { pages, pageParams } = query.state.data;\n const next = options.getNextPageParam(\n pages[pages.length - 1],\n pages,\n pageParams[pageParams.length - 1],\n pageParams,\n );\n\n const direction = deepEqual(pageParam, next) ? 'forward' : 'backward';\n\n const result = await query.fetch(\n { ...query.options, meta: { pageParam } },\n { meta: { fetchMore: { direction } } },\n );\n\n const pageIndex = result.pageParams.findIndex((param) =>\n deepEqual(param, pageParam),\n );\n\n return result.pages[pageIndex];\n }\n\n /**\n * Invalidate queries serviced by this data service.\n *\n * @param filters - Optional filter for selecting specific queries.\n * @param options - Additional optional options for query invalidations.\n * @returns Nothing.\n */\n async invalidateQueries(\n filters?: InvalidateQueryFilters<QueryKey>,\n options?: InvalidateOptions,\n ): Promise<void> {\n return this.#queryClient.invalidateQueries(filters, options);\n }\n\n /**\n * Initialize the service, rehydrating the cache with persisted data if possible.\n */\n init(): void {\n this.#loadCache().catch(\n /* istanbul ignore next */\n (error) => this.#messenger.captureException?.(error),\n );\n }\n\n /**\n * Prepares the service for garbage collection. This should be extended\n * by any subclasses to clean up any additional connections or events.\n */\n destroy(): void {\n this.#debouncedPersist?.cancel();\n this.#queryCacheUnsubscribe();\n this.#queryClient.clear();\n this.messenger.clearSubscriptions();\n this.messenger.clearActions();\n }\n\n /**\n * Publish `cacheUpdated` events when a given query changes.\n *\n * @param hash The hash of the query.\n * @param type The type of cache update.\n */\n #publishCacheUpdate(hash: string, type: CacheUpdatedType): void {\n const state =\n type === 'added' || type === 'updated'\n ? dehydrate(this.#queryClient, {\n shouldDehydrateQuery: (query) => query.queryHash === hash,\n })\n : null;\n\n this.#messenger.publish(\n `${this.name}:cacheUpdated` as const,\n {\n type,\n hash,\n state,\n } as DataServiceCacheUpdatedPayload,\n );\n\n this.#messenger.publish(\n `${this.name}:cacheUpdated:${hash}` as const,\n {\n type,\n state,\n } as DataServiceGranularCacheUpdatedPayload,\n );\n }\n\n /**\n * Persist the query client cache using the StorageService, if the cache is not empty.\n *\n * @returns Nothing.\n */\n async #persistCache(): Promise<void> {\n const state = dehydrate(this.#queryClient, {\n // This is the default, but we specify it to be explicit.\n shouldDehydrateQuery: (query) => query.state.status === 'success',\n });\n\n if (state.queries.length === 0 && state.mutations.length === 0) {\n await this.#externalMessenger.call(\n 'StorageService:removeItem',\n this.name,\n STORAGE_SERVICE_KEY,\n );\n return;\n }\n\n const cache: PersistedCache = {\n timestamp: Date.now(),\n state,\n };\n\n await this.#externalMessenger.call(\n 'StorageService:setItem',\n this.name,\n STORAGE_SERVICE_KEY,\n cache as unknown as Json,\n );\n }\n\n /**\n * Load the query client cache from the StorageService, if persistence is configured\n * and the persisted cache is not expired.\n *\n * @returns Nothing.\n */\n async #loadCache(): Promise<void> {\n if (!this.#persistenceConfig) {\n return;\n }\n\n const { result: untypedCache } = await this.#externalMessenger.call(\n 'StorageService:getItem',\n this.name,\n STORAGE_SERVICE_KEY,\n );\n\n if (!untypedCache) {\n return;\n }\n\n const cache = untypedCache as unknown as PersistedCache;\n\n if (Date.now() - cache.timestamp >= this.#persistenceConfig.maxAge) {\n await this.#externalMessenger.call(\n 'StorageService:removeItem',\n this.name,\n STORAGE_SERVICE_KEY,\n );\n return;\n }\n\n hydrate(this.#queryClient, cache.state);\n }\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { CircuitState } from
|
|
2
|
-
import type { CircuitBreakerPolicy, Event as CockatielEvent, FailureReason, IBackoffFactory, IPolicy, Policy, RetryPolicy } from
|
|
1
|
+
import { CircuitState } from 'cockatiel';
|
|
2
|
+
import type { CircuitBreakerPolicy, Event as CockatielEvent, FailureReason, IBackoffFactory, IPolicy, Policy, RetryPolicy } from 'cockatiel';
|
|
3
3
|
/**
|
|
4
4
|
* The options for `createServicePolicy`.
|
|
5
5
|
*/
|
|
@@ -176,4 +176,4 @@ export declare const DEFAULT_DEGRADED_THRESHOLD = 5000;
|
|
|
176
176
|
* ```
|
|
177
177
|
*/
|
|
178
178
|
export declare function createServicePolicy(options?: CreateServicePolicyOptions): ServicePolicy;
|
|
179
|
-
//# sourceMappingURL=createServicePolicy.d.
|
|
179
|
+
//# sourceMappingURL=createServicePolicy.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"createServicePolicy.d.ts","sourceRoot":"","sources":["../src/createServicePolicy.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,YAAY,EASb,MAAM,WAAW,CAAC;AACnB,OAAO,KAAK,EACV,oBAAoB,EACpB,KAAK,IAAI,cAAc,EACvB,aAAa,EACb,eAAe,EACf,OAAO,EACP,MAAM,EACN,WAAW,EACZ,MAAM,WAAW,CAAC;AAEnB;;GAEG;AACH,MAAM,MAAM,0BAA0B,GAAG;IACvC;;;;OAIG;IACH,OAAO,CAAC,EAAE,eAAe,CAAC,OAAO,CAAC,CAAC;IACnC;;;OAGG;IACH,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B;;;OAGG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B;;OAEG;IACH,gBAAgB,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,OAAO,CAAC;IAC/C;;;OAGG;IACH,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;;OAKG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,aAAa,GAAG,OAAO,GAAG;IACpC;;;OAGG;IACH,oBAAoB,EAAE,oBAAoB,CAAC;IAC3C;;;OAGG;IACH,oBAAoB,EAAE,MAAM,CAAC;IAC7B;;OAEG;IACH,eAAe,EAAE,MAAM,YAAY,CAAC;IACpC;;;;OAIG;IACH,+BAA+B,EAAE,MAAM,MAAM,GAAG,IAAI,CAAC;IACrD;;;OAGG;IACH,KAAK,EAAE,MAAM,IAAI,CAAC;IAClB;;OAEG;IACH,WAAW,EAAE,WAAW,CAAC;IACzB;;;OAGG;IACH,OAAO,EAAE,oBAAoB,CAAC,SAAS,CAAC,CAAC;IACzC;;;;;;OAMG;IACH,UAAU,EAAE,cAAc,CAAC,aAAa,CAAC,OAAO,CAAC,GAAG;QAAE,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAC1E;;;;OAIG;IACH,WAAW,EAAE,cAAc,CAAC,IAAI,CAAC,CAAC;IAClC;;;;OAIG;IACH,OAAO,EAAE,WAAW,CAAC,SAAS,CAAC,CAAC;CACjC,CAAC;AAiCF;;;GAGG;AACH,eAAO,MAAM,mBAAmB,IAAI,CAAC;AAErC;;;;;GAKG;AACH,eAAO,MAAM,gCAAgC,QAAgC,CAAC;AAE9E;;;GAGG;AACH,eAAO,MAAM,8BAA8B,QAAiB,CAAC;AAE7D;;;GAGG;AACH,eAAO,MAAM,0BAA0B,OAAQ,CAAC;AAqChD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiDG;AACH,wBAAgB,mBAAmB,CACjC,OAAO,GAAE,0BAA+B,GACvC,aAAa,CAsIf"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { CircuitState, EventEmitter as CockatielEventEmitter, ConsecutiveBreaker, ExponentialBackoff, circuitBreaker, handleAll, handleWhen, retry, wrap } from
|
|
1
|
+
import { CircuitState, EventEmitter as CockatielEventEmitter, ConsecutiveBreaker, ExponentialBackoff, circuitBreaker, handleAll, handleWhen, retry, wrap, } from 'cockatiel';
|
|
2
2
|
/**
|
|
3
3
|
* Availability statuses that the service can be in.
|
|
4
4
|
*
|
|
@@ -31,7 +31,7 @@ export const DEFAULT_CIRCUIT_BREAK_DURATION = 30 * 60 * 1000;
|
|
|
31
31
|
* The default length of time (in milliseconds) that governs when the service is
|
|
32
32
|
* regarded as degraded (affecting when `onDegraded` is called).
|
|
33
33
|
*/
|
|
34
|
-
export const DEFAULT_DEGRADED_THRESHOLD =
|
|
34
|
+
export const DEFAULT_DEGRADED_THRESHOLD = 5_000;
|
|
35
35
|
const defaultIsServiceFailure = (error) => {
|
|
36
36
|
if (typeof error === 'object' &&
|
|
37
37
|
error !== null &&
|
|
@@ -221,4 +221,4 @@ export function createServicePolicy(options = {}) {
|
|
|
221
221
|
onRetry,
|
|
222
222
|
};
|
|
223
223
|
}
|
|
224
|
-
//# sourceMappingURL=createServicePolicy.
|
|
224
|
+
//# sourceMappingURL=createServicePolicy.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"createServicePolicy.js","sourceRoot":"","sources":["../src/createServicePolicy.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,YAAY,EACZ,YAAY,IAAI,qBAAqB,EACrC,kBAAkB,EAClB,kBAAkB,EAClB,cAAc,EACd,SAAS,EACT,UAAU,EACV,KAAK,EACL,IAAI,GACL,MAAM,WAAW,CAAC;AA6HnB;;;;GAIG;AACH,MAAM,qBAAqB,GAAG;IAC5B,SAAS,EAAE,WAAW;IACtB,QAAQ,EAAE,UAAU;IACpB,WAAW,EAAE,aAAa;IAC1B,OAAO,EAAE,SAAS;CACV,CAAC;AAUX;;;GAGG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,CAAC;AAErC;;;;;GAKG;AACH,MAAM,CAAC,MAAM,gCAAgC,GAAG,CAAC,CAAC,GAAG,mBAAmB,CAAC,GAAG,CAAC,CAAC;AAE9E;;;GAGG;AACH,MAAM,CAAC,MAAM,8BAA8B,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAE7D;;;GAGG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAG,KAAK,CAAC;AAEhD,MAAM,uBAAuB,GAAG,CAAC,K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C;QACnD,8BAA8B;QAC9B,OAAO,EAAE,CAAC;QAEV,2CAA2C;QAC3C,kBAAkB,CAAC,OAAO,EAAE,CAAC;QAE7B,2EAA2E;QAC3E,2DAA2D;QAC3D,kBAAkB,GAAG,qBAAqB,CAAC,OAAO,CAAC;IACrD,CAAC,CAAC;IAEF,OAAO;QACL,GAAG,MAAM;QACT,oBAAoB;QACpB,oBAAoB;QACpB,eAAe;QACf,+BAA+B;QAC/B,KAAK;QACL,WAAW;QACX,OAAO;QACP,UAAU;QACV,WAAW;QACX,OAAO;KACR,CAAC;AACJ,CAAC","sourcesContent":["import {\n CircuitState,\n EventEmitter as CockatielEventEmitter,\n ConsecutiveBreaker,\n ExponentialBackoff,\n circuitBreaker,\n handleAll,\n handleWhen,\n retry,\n wrap,\n} from 'cockatiel';\nimport type {\n CircuitBreakerPolicy,\n Event as CockatielEvent,\n FailureReason,\n IBackoffFactory,\n IPolicy,\n Policy,\n RetryPolicy,\n} from 'cockatiel';\n\n/**\n * The options for `createServicePolicy`.\n */\nexport type CreateServicePolicyOptions = {\n /**\n * The backoff strategy to use. Mainly useful for testing so that a constant\n * backoff can be used when mocking timers. Defaults to an instance of\n * ExponentialBackoff.\n */\n backoff?: IBackoffFactory<unknown>;\n /**\n * The length of time (in milliseconds) to pause retries of the action after\n * the number of failures reaches `maxConsecutiveFailures`.\n */\n circuitBreakDuration?: number;\n /**\n * The length of time (in milliseconds) that governs when the service is\n * regarded as degraded (affecting when `onDegraded` is called).\n */\n degradedThreshold?: number;\n /**\n * Predicate function for when an error should be considered a service failure.\n */\n isServiceFailure?: (error: unknown) => boolean;\n /**\n * The maximum number of times that the service is allowed to fail before\n * pausing further retries.\n */\n maxConsecutiveFailures?: number;\n /**\n * The maximum number of times that a failing service should be re-invoked\n * before giving up.\n */\n maxRetries?: number;\n /**\n * The policy used to control when the service should be retried based on\n * either the result of the service or an error that it throws. For instance,\n * you could use this to retry only certain errors. See `handleWhen` and\n * friends from Cockatiel for more.\n */\n retryFilterPolicy?: Policy;\n};\n\n/**\n * The service policy object.\n */\nexport type ServicePolicy = IPolicy & {\n /**\n * The Cockatiel circuit breaker policy that the service policy uses\n * internally.\n */\n circuitBreakerPolicy: CircuitBreakerPolicy;\n /**\n * The amount of time to pause requests to the service if the number of\n * maximum consecutive failures is reached.\n */\n circuitBreakDuration: number;\n /**\n * @returns The state of the underlying circuit.\n */\n getCircuitState: () => CircuitState;\n /**\n * If the circuit is open and ongoing requests are paused, returns the number\n * of milliseconds before the requests will be attempted again. If the circuit\n * is not open, returns null.\n */\n getRemainingCircuitOpenDuration: () => number | null;\n /**\n * Resets the internal circuit breaker policy (if it is open, it will now be\n * closed).\n */\n reset: () => void;\n /**\n * The Cockatiel retry policy that the service policy uses internally.\n */\n retryPolicy: RetryPolicy;\n /**\n * A function which is called when the number of times that the service fails\n * in a row meets the set maximum number of consecutive failures.\n */\n onBreak: CircuitBreakerPolicy['onBreak'];\n /**\n * A function which is called in two circumstances: 1) when the service\n * succeeds before the maximum number of consecutive failures is reached, but\n * takes more time than the `degradedThreshold` to run, or 2) if the service\n * never succeeds before the retry policy gives up and before the maximum\n * number of consecutive failures has been reached.\n */\n onDegraded: CockatielEvent<FailureReason<unknown> | { duration: number }>;\n /**\n * A function which is called when the service succeeds for the first time,\n * or when the service fails enough times to cause the circuit to break and\n * then recovers.\n */\n onAvailable: CockatielEvent<void>;\n /**\n * A function which will be called by the retry policy each time the service\n * fails and the policy kicks off a timer to re-run the service. This is\n * primarily useful in tests where we are mocking timers.\n */\n onRetry: RetryPolicy['onRetry'];\n};\n\n/**\n * Parts of the circuit breaker's internal and external state as necessary in\n * order to compute the time remaining before the circuit will reopen.\n */\ntype InternalCircuitState =\n | {\n state: CircuitState.Open;\n openedAt: number;\n }\n | { state: Exclude<CircuitState, CircuitState.Open> };\n\n/**\n * Availability statuses that the service can be in.\n *\n * Used to keep track of whether the `onAvailable` event should be fired.\n */\nconst AVAILABILITY_STATUSES = {\n Available: 'available',\n Degraded: 'degraded',\n Unavailable: 'unavailable',\n Unknown: 'unknown',\n} as const;\n\n/**\n * Availability statuses that the service can be in.\n *\n * Used to keep track of whether the `onAvailable` event should be fired.\n */\ntype AvailabilityStatus =\n (typeof AVAILABILITY_STATUSES)[keyof typeof AVAILABILITY_STATUSES];\n\n/**\n * The maximum number of times that a failing service should be re-run before\n * giving up.\n */\nexport const DEFAULT_MAX_RETRIES = 3;\n\n/**\n * The maximum number of times that the service is allowed to fail before\n * pausing further retries. This is set to a value such that if given a\n * service that continually fails, the policy needs to be executed 3 times\n * before further retries are paused.\n */\nexport const DEFAULT_MAX_CONSECUTIVE_FAILURES = (1 + DEFAULT_MAX_RETRIES) * 3;\n\n/**\n * The default length of time (in milliseconds) to temporarily pause retries of\n * the service after enough consecutive failures.\n */\nexport const DEFAULT_CIRCUIT_BREAK_DURATION = 30 * 60 * 1000;\n\n/**\n * The default length of time (in milliseconds) that governs when the service is\n * regarded as degraded (affecting when `onDegraded` is called).\n */\nexport const DEFAULT_DEGRADED_THRESHOLD = 5_000;\n\nconst defaultIsServiceFailure = (error: unknown): boolean => {\n if (\n typeof error === 'object' &&\n error !== null &&\n 'httpStatus' in error &&\n typeof error.httpStatus === 'number'\n ) {\n return error.httpStatus >= 500;\n }\n\n // If the error is not an object, or doesn't have a numeric httpStatus\n // property, consider it a service failure (e.g., network errors, timeouts,\n // etc.)\n return true;\n};\n\n/**\n * The circuit breaker policy inside of the Cockatiel library exposes some of\n * its state, but not all of it. Notably, the time that the circuit opened is\n * not publicly accessible. So we have to record this ourselves.\n *\n * This function therefore allows us to obtain the circuit breaker state that we\n * wish we could access.\n *\n * @param state - The public state of a circuit breaker policy.\n * @returns if the circuit is open, the state of the circuit breaker policy plus\n * the time that it opened, otherwise just the circuit state.\n */\nfunction getInternalCircuitState(state: CircuitState): InternalCircuitState {\n if (state === CircuitState.Open) {\n return { state, openedAt: Date.now() };\n }\n return { state };\n}\n\n/**\n * Constructs an object exposing an `execute` method which, given a function —\n * hereafter called the \"service\" — will retry that service with ever increasing\n * delays until it succeeds. If the policy detects too many consecutive\n * failures, it will block further retries until a designated time period has\n * passed; this particular behavior is primarily designed for services that wrap\n * API calls so as not to make needless HTTP requests when the API is down and\n * to be able to recover when the API comes back up. In addition, hooks allow\n * for responding to certain events, one of which can be used to detect when an\n * HTTP request is performing slowly.\n *\n * Internally, this function makes use of the retry and circuit breaker policies\n * from the [Cockatiel](https://www.npmjs.com/package/cockatiel) library; see\n * there for more.\n *\n * @param options - The options to this function. See\n * {@link CreateServicePolicyOptions}.\n * @returns The service policy.\n * @example\n * This function is designed to be used in the context of a service class like\n * this:\n * ``` ts\n * class Service {\n * constructor() {\n * this.#policy = createServicePolicy({\n * maxRetries: 3,\n * retryFilterPolicy: handleWhen((error) => {\n * return error.message.includes('oops');\n * }),\n * maxConsecutiveFailures: 3,\n * circuitBreakDuration: 5000,\n * degradedThreshold: 2000,\n * onBreak: () => {\n * console.log('Circuit broke');\n * },\n * onDegraded: () => {\n * console.log('Service is degraded');\n * },\n * });\n * }\n *\n * async fetch() {\n * return await this.#policy.execute(async () => {\n * const response = await fetch('https://some/url');\n * return await response.json();\n * });\n * }\n * }\n * ```\n */\nexport function createServicePolicy(\n options: CreateServicePolicyOptions = {},\n): ServicePolicy {\n const {\n maxRetries = DEFAULT_MAX_RETRIES,\n retryFilterPolicy = handleAll,\n maxConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES,\n circuitBreakDuration = DEFAULT_CIRCUIT_BREAK_DURATION,\n degradedThreshold = DEFAULT_DEGRADED_THRESHOLD,\n backoff = new ExponentialBackoff(),\n isServiceFailure = defaultIsServiceFailure,\n } = options;\n\n let availabilityStatus: AvailabilityStatus = AVAILABILITY_STATUSES.Unknown;\n\n const retryPolicy = retry(retryFilterPolicy, {\n // Note that although the option here is called \"max attempts\", it's really\n // maximum number of *retries* (attempts past the initial attempt).\n maxAttempts: maxRetries,\n // Retries of the service will be executed following ever increasing delays,\n // determined by a backoff formula.\n backoff,\n });\n const onRetry = retryPolicy.onRetry.bind(retryPolicy);\n\n const consecutiveBreaker = new ConsecutiveBreaker(maxConsecutiveFailures);\n const circuitBreakerPolicy = circuitBreaker(handleWhen(isServiceFailure), {\n // While the circuit is open, any additional invocations of the service\n // passed to the policy (either via automatic retries or by manually\n // executing the policy again) will result in a BrokenCircuitError. This\n // will remain the case until `circuitBreakDuration` passes, after which the\n // service will be allowed to run again. If the service succeeds, the\n // circuit will close, otherwise it will remain open.\n halfOpenAfter: circuitBreakDuration,\n breaker: consecutiveBreaker,\n });\n\n let internalCircuitState: InternalCircuitState = getInternalCircuitState(\n circuitBreakerPolicy.state,\n );\n circuitBreakerPolicy.onStateChange((state) => {\n internalCircuitState = getInternalCircuitState(state);\n });\n\n circuitBreakerPolicy.onBreak(() => {\n availabilityStatus = AVAILABILITY_STATUSES.Unavailable;\n });\n const onBreak = circuitBreakerPolicy.onBreak.bind(circuitBreakerPolicy);\n\n const onDegradedEventEmitter = new CockatielEventEmitter<\n FailureReason<unknown> | { duration: number }\n >();\n const onDegraded = onDegradedEventEmitter.addListener;\n\n const onAvailableEventEmitter = new CockatielEventEmitter<void>();\n const onAvailable = onAvailableEventEmitter.addListener;\n\n retryPolicy.onGiveUp((data) => {\n if (circuitBreakerPolicy.state === CircuitState.Closed) {\n availabilityStatus = AVAILABILITY_STATUSES.Degraded;\n onDegradedEventEmitter.emit(data);\n }\n });\n retryPolicy.onSuccess(({ duration }) => {\n if (circuitBreakerPolicy.state === CircuitState.Closed) {\n if (duration > degradedThreshold) {\n availabilityStatus = AVAILABILITY_STATUSES.Degraded;\n onDegradedEventEmitter.emit({ duration });\n } else if (availabilityStatus !== AVAILABILITY_STATUSES.Available) {\n availabilityStatus = AVAILABILITY_STATUSES.Available;\n onAvailableEventEmitter.emit();\n }\n }\n });\n\n // Every time the retry policy makes an attempt, it executes the circuit\n // breaker policy, which executes the service.\n //\n // Calling:\n //\n // policy.execute(() => {\n // // do what the service does\n // })\n //\n // is equivalent to:\n //\n // retryPolicy.execute(() => {\n // circuitBreakerPolicy.execute(() => {\n // // do what the service does\n // });\n // });\n //\n // So if the retry policy succeeds or fails, it is because the circuit breaker\n // policy succeeded or failed. And if there are any event listeners registered\n // on the retry policy, by the time they are called, the state of the circuit\n // breaker will have already changed.\n const policy = wrap(retryPolicy, circuitBreakerPolicy);\n\n const getRemainingCircuitOpenDuration = (): number | null => {\n if (internalCircuitState.state === CircuitState.Open) {\n return internalCircuitState.openedAt + circuitBreakDuration - Date.now();\n }\n return null;\n };\n\n const getCircuitState = (): CircuitState => {\n return circuitBreakerPolicy.state;\n };\n\n const reset = (): void => {\n // Set the state of the policy to \"isolated\" regardless of its current state\n const { dispose } = circuitBreakerPolicy.isolate();\n // Reset the state to \"closed\"\n dispose();\n\n // Reset the counter on the breaker as well\n consecutiveBreaker.success();\n\n // Re-initialize the availability status so that if the service is executed\n // successfully, onAvailable listeners will be called again\n availabilityStatus = AVAILABILITY_STATUSES.Unknown;\n };\n\n return {\n ...policy,\n circuitBreakerPolicy,\n circuitBreakDuration,\n getCircuitState,\n getRemainingCircuitOpenDuration,\n reset,\n retryPolicy,\n onBreak,\n onDegraded,\n onAvailable,\n onRetry,\n };\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
export type { Event as CockatielEvent, FailureReason as CockatielFailureReason, } from
|
|
2
|
-
export { BrokenCircuitError, EventEmitter as CockatielEventEmitter, CircuitState, ConstantBackoff, ExponentialBackoff, handleAll, handleWhen, } from
|
|
3
|
-
export type { DataServiceActions, DataServiceEvents, DataServiceCacheUpdatedPayload, DataServiceGranularCacheUpdatedPayload, DataServiceInvalidateQueriesAction, DataServiceCacheUpdatedEvent, DataServiceGranularCacheUpdatedEvent, QueryKey,
|
|
4
|
-
export { BaseDataService } from
|
|
5
|
-
export { DEFAULT_CIRCUIT_BREAK_DURATION, DEFAULT_DEGRADED_THRESHOLD, DEFAULT_MAX_CONSECUTIVE_FAILURES, DEFAULT_MAX_RETRIES, createServicePolicy, } from
|
|
6
|
-
export type { CreateServicePolicyOptions, ServicePolicy, } from
|
|
7
|
-
//# sourceMappingURL=index.d.
|
|
1
|
+
export type { Event as CockatielEvent, FailureReason as CockatielFailureReason, } from 'cockatiel';
|
|
2
|
+
export { BrokenCircuitError, EventEmitter as CockatielEventEmitter, CircuitState, ConstantBackoff, ExponentialBackoff, handleAll, handleWhen, } from 'cockatiel';
|
|
3
|
+
export type { DataServiceActions, DataServiceEvents, DataServiceCacheUpdatedPayload, DataServiceGranularCacheUpdatedPayload, DataServiceInvalidateQueriesAction, DataServiceCacheUpdatedEvent, DataServiceGranularCacheUpdatedEvent, QueryKey, PersistenceConfiguration, } from './BaseDataService.js';
|
|
4
|
+
export { BaseDataService } from './BaseDataService.js';
|
|
5
|
+
export { DEFAULT_CIRCUIT_BREAK_DURATION, DEFAULT_DEGRADED_THRESHOLD, DEFAULT_MAX_CONSECUTIVE_FAILURES, DEFAULT_MAX_RETRIES, createServicePolicy, } from './createServicePolicy.js';
|
|
6
|
+
export type { CreateServicePolicyOptions, ServicePolicy, } from './createServicePolicy.js';
|
|
7
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,KAAK,IAAI,cAAc,EACvB,aAAa,IAAI,sBAAsB,GACxC,MAAM,WAAW,CAAC;AAEnB,OAAO,EACL,kBAAkB,EAClB,YAAY,IAAI,qBAAqB,EACrC,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,SAAS,EACT,UAAU,GACX,MAAM,WAAW,CAAC;AAEnB,YAAY,EACV,kBAAkB,EAClB,iBAAiB,EACjB,8BAA8B,EAC9B,sCAAsC,EACtC,kCAAkC,EAClC,4BAA4B,EAC5B,oCAAoC,EACpC,QAAQ,EACR,wBAAwB,GACzB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAEvD,OAAO,EACL,8BAA8B,EAC9B,0BAA0B,EAC1B,gCAAgC,EAChC,mBAAmB,EACnB,mBAAmB,GACpB,MAAM,0BAA0B,CAAC;AAClC,YAAY,EACV,0BAA0B,EAC1B,aAAa,GACd,MAAM,0BAA0B,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { BrokenCircuitError, EventEmitter as CockatielEventEmitter, CircuitState, ConstantBackoff, ExponentialBackoff, handleAll, handleWhen } from
|
|
2
|
-
export { BaseDataService } from
|
|
3
|
-
export { DEFAULT_CIRCUIT_BREAK_DURATION, DEFAULT_DEGRADED_THRESHOLD, DEFAULT_MAX_CONSECUTIVE_FAILURES, DEFAULT_MAX_RETRIES, createServicePolicy } from
|
|
4
|
-
//# sourceMappingURL=index.
|
|
1
|
+
export { BrokenCircuitError, EventEmitter as CockatielEventEmitter, CircuitState, ConstantBackoff, ExponentialBackoff, handleAll, handleWhen, } from 'cockatiel';
|
|
2
|
+
export { BaseDataService } from './BaseDataService.js';
|
|
3
|
+
export { DEFAULT_CIRCUIT_BREAK_DURATION, DEFAULT_DEGRADED_THRESHOLD, DEFAULT_MAX_CONSECUTIVE_FAILURES, DEFAULT_MAX_RETRIES, createServicePolicy, } from './createServicePolicy.js';
|
|
4
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,kBAAkB,EAClB,YAAY,IAAI,qBAAqB,EACrC,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,SAAS,EACT,UAAU,GACX,MAAM,WAAW,CAAC;AAanB,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAEvD,OAAO,EACL,8BAA8B,EAC9B,0BAA0B,EAC1B,gCAAgC,EAChC,mBAAmB,EACnB,mBAAmB,GACpB,MAAM,0BAA0B,CAAC","sourcesContent":["export type {\n Event as CockatielEvent,\n FailureReason as CockatielFailureReason,\n} from 'cockatiel';\n\nexport {\n BrokenCircuitError,\n EventEmitter as CockatielEventEmitter,\n CircuitState,\n ConstantBackoff,\n ExponentialBackoff,\n handleAll,\n handleWhen,\n} from 'cockatiel';\n\nexport type {\n DataServiceActions,\n DataServiceEvents,\n DataServiceCacheUpdatedPayload,\n DataServiceGranularCacheUpdatedPayload,\n DataServiceInvalidateQueriesAction,\n DataServiceCacheUpdatedEvent,\n DataServiceGranularCacheUpdatedEvent,\n QueryKey,\n PersistenceConfiguration,\n} from './BaseDataService.js';\nexport { BaseDataService } from './BaseDataService.js';\n\nexport {\n DEFAULT_CIRCUIT_BREAK_DURATION,\n DEFAULT_DEGRADED_THRESHOLD,\n DEFAULT_MAX_CONSECUTIVE_FAILURES,\n DEFAULT_MAX_RETRIES,\n createServicePolicy,\n} from './createServicePolicy.js';\nexport type {\n CreateServicePolicyOptions,\n ServicePolicy,\n} from './createServicePolicy.js';\n"]}
|
package/dist/utils.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { Struct } from '@metamask/superstruct';
|
|
2
|
+
import type { QueryKey } from './BaseDataService.js';
|
|
3
|
+
/**
|
|
4
|
+
* Process query responses, validating them using Superstruct if a struct is defined.
|
|
5
|
+
*
|
|
6
|
+
* @param queryKey - The query key.
|
|
7
|
+
* @param response - The query response
|
|
8
|
+
* @param struct - The struct defining the schema for the query response.
|
|
9
|
+
* @returns The query response, coerced by Superstruct if needed.
|
|
10
|
+
* @throws If the query response does not match the struct.
|
|
11
|
+
*/
|
|
12
|
+
export declare function processQueryResponse<Response>(queryKey: QueryKey, response: Response, struct?: Struct<Response>): Response;
|
|
13
|
+
//# sourceMappingURL=utils.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAY,MAAM,uBAAuB,CAAC;AAEzD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAErD;;;;;;;;GAQG;AACH,wBAAgB,oBAAoB,CAAC,QAAQ,EAC3C,QAAQ,EAAE,QAAQ,EAClB,QAAQ,EAAE,QAAQ,EAClB,MAAM,CAAC,EAAE,MAAM,CAAC,QAAQ,CAAC,GACxB,QAAQ,CAcV"}
|
package/dist/utils.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { validate } from '@metamask/superstruct';
|
|
2
|
+
/**
|
|
3
|
+
* Process query responses, validating them using Superstruct if a struct is defined.
|
|
4
|
+
*
|
|
5
|
+
* @param queryKey - The query key.
|
|
6
|
+
* @param response - The query response
|
|
7
|
+
* @param struct - The struct defining the schema for the query response.
|
|
8
|
+
* @returns The query response, coerced by Superstruct if needed.
|
|
9
|
+
* @throws If the query response does not match the struct.
|
|
10
|
+
*/
|
|
11
|
+
export function processQueryResponse(queryKey, response, struct) {
|
|
12
|
+
if (!struct) {
|
|
13
|
+
return response;
|
|
14
|
+
}
|
|
15
|
+
const [error, result] = validate(response, struct);
|
|
16
|
+
if (error) {
|
|
17
|
+
throw new Error(`Query function for "${queryKey[0]}" returned an unexpected response: ${error.message}.`);
|
|
18
|
+
}
|
|
19
|
+
return result;
|
|
20
|
+
}
|
|
21
|
+
//# sourceMappingURL=utils.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAIzD;;;;;;;;GAQG;AACH,MAAM,UAAU,oBAAoB,CAClC,QAAkB,EAClB,QAAkB,EAClB,MAAyB;IAEzB,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,GAAG,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;IAEnD,IAAI,KAAK,EAAE,CAAC;QACV,MAAM,IAAI,KAAK,CACb,uBAAuB,QAAQ,CAAC,CAAC,CAAC,sCAAsC,KAAK,CAAC,OAAO,GAAG,CACzF,CAAC;IACJ,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { Struct, validate } from '@metamask/superstruct';\n\nimport type { QueryKey } from './BaseDataService.js';\n\n/**\n * Process query responses, validating them using Superstruct if a struct is defined.\n *\n * @param queryKey - The query key.\n * @param response - The query response\n * @param struct - The struct defining the schema for the query response.\n * @returns The query response, coerced by Superstruct if needed.\n * @throws If the query response does not match the struct.\n */\nexport function processQueryResponse<Response>(\n queryKey: QueryKey,\n response: Response,\n struct?: Struct<Response>,\n): Response {\n if (!struct) {\n return response;\n }\n\n const [error, result] = validate(response, struct);\n\n if (error) {\n throw new Error(\n `Query function for \"${queryKey[0]}\" returned an unexpected response: ${error.message}.`,\n );\n }\n\n return result;\n}\n"]}
|