@metamask-previews/base-data-service 1.0.0-preview-8bfa290fb → 1.0.0-preview-ec24abb79
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 +0 -17
- package/dist/BaseDataService.cjs +11 -86
- package/dist/BaseDataService.cjs.map +1 -1
- package/dist/BaseDataService.d.cts +4 -35
- package/dist/BaseDataService.d.cts.map +1 -1
- package/dist/BaseDataService.d.mts +4 -35
- package/dist/BaseDataService.d.mts.map +1 -1
- package/dist/BaseDataService.mjs +13 -88
- package/dist/BaseDataService.mjs.map +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/utils.cjs +1 -32
- package/dist/utils.cjs.map +1 -1
- package/dist/utils.d.cts +1 -14
- package/dist/utils.d.cts.map +1 -1
- package/dist/utils.d.mts +1 -14
- package/dist/utils.d.mts.map +1 -1
- package/dist/utils.mjs +0 -30
- package/dist/utils.mjs.map +1 -1
- package/package.json +2 -2
- 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/CHANGELOG.md
CHANGED
|
@@ -7,23 +7,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
-
### Added
|
|
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))
|
|
17
|
-
|
|
18
|
-
### Changed
|
|
19
|
-
|
|
20
|
-
- Bump `@metamask/utils` from `^11.11.0` to `^11.12.0` ([#10076](https://github.com/MetaMask/core/pull/10076))
|
|
21
|
-
|
|
22
|
-
### Fixed
|
|
23
|
-
|
|
24
|
-
- Allow `QueryKey` to be not only mutable, but also readonly ([#9445](https://github.com/MetaMask/core/pull/9445))
|
|
25
|
-
- This allows the `queryKey` argument to `fetchQuery` or `fetchInfiniteQuery` to be extracted to its own variable (as long as `as const` is used to type the query key).
|
|
26
|
-
|
|
27
10
|
## [1.0.0]
|
|
28
11
|
|
|
29
12
|
### Added
|
package/dist/BaseDataService.cjs
CHANGED
|
@@ -13,7 +13,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
13
13
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
14
14
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
15
15
|
};
|
|
16
|
-
var _BaseDataService_instances, _BaseDataService_messenger, _BaseDataService_externalMessenger, _BaseDataService_policy, _BaseDataService_queryClient, _BaseDataService_queryCacheUnsubscribe,
|
|
16
|
+
var _BaseDataService_instances, _BaseDataService_messenger, _BaseDataService_externalMessenger, _BaseDataService_policy, _BaseDataService_queryClient, _BaseDataService_queryCacheUnsubscribe, _BaseDataService_debouncedPersist, _BaseDataService_persistenceConfig, _BaseDataService_publishCacheUpdate, _BaseDataService_persistCache, _BaseDataService_loadCache;
|
|
17
17
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
18
18
|
exports.BaseDataService = exports.STORAGE_SERVICE_KEY = void 0;
|
|
19
19
|
const messenger_1 = require("@metamask/messenger");
|
|
@@ -23,20 +23,13 @@ const query_core_1 = require("@tanstack/query-core");
|
|
|
23
23
|
const fast_deep_equal_1 = __importDefault(require("fast-deep-equal"));
|
|
24
24
|
const lodash_1 = require("lodash");
|
|
25
25
|
const createServicePolicy_js_1 = require("./createServicePolicy.cjs");
|
|
26
|
-
const loggers_js_1 = require("./loggers.cjs");
|
|
27
26
|
const utils_js_1 = require("./utils.cjs");
|
|
28
|
-
|
|
29
|
-
/*
|
|
30
|
-
* Defaults to apply to all data service queries if no default option specified.
|
|
31
|
-
*/
|
|
27
|
+
// Defaults to apply to all data service queries if no default option specified
|
|
32
28
|
const QUERY_CLIENT_DEFAULTS = {
|
|
33
29
|
queries: {
|
|
34
30
|
retry: false,
|
|
35
31
|
staleTime: (0, utils_1.inMilliseconds)(1, utils_1.Duration.Minute),
|
|
36
32
|
},
|
|
37
|
-
mutations: {
|
|
38
|
-
retry: false,
|
|
39
|
-
},
|
|
40
33
|
};
|
|
41
34
|
exports.STORAGE_SERVICE_KEY = 'cache';
|
|
42
35
|
class BaseDataService {
|
|
@@ -47,7 +40,6 @@ class BaseDataService {
|
|
|
47
40
|
_BaseDataService_policy.set(this, void 0);
|
|
48
41
|
_BaseDataService_queryClient.set(this, void 0);
|
|
49
42
|
_BaseDataService_queryCacheUnsubscribe.set(this, void 0);
|
|
50
|
-
_BaseDataService_mutationCacheUnsubscribe.set(this, void 0);
|
|
51
43
|
_BaseDataService_debouncedPersist.set(this, void 0);
|
|
52
44
|
_BaseDataService_persistenceConfig.set(this, void 0);
|
|
53
45
|
this.name = name;
|
|
@@ -65,10 +57,7 @@ class BaseDataService {
|
|
|
65
57
|
...QUERY_CLIENT_DEFAULTS.queries,
|
|
66
58
|
...queryClientConfig.defaultOptions?.queries,
|
|
67
59
|
},
|
|
68
|
-
mutations:
|
|
69
|
-
...QUERY_CLIENT_DEFAULTS.mutations,
|
|
70
|
-
...queryClientConfig.defaultOptions?.mutations,
|
|
71
|
-
},
|
|
60
|
+
mutations: queryClientConfig.defaultOptions?.mutations,
|
|
72
61
|
},
|
|
73
62
|
}), "f");
|
|
74
63
|
__classPrivateFieldSet(this, _BaseDataService_persistenceConfig, persistenceConfig, "f");
|
|
@@ -86,21 +75,8 @@ class BaseDataService {
|
|
|
86
75
|
__classPrivateFieldSet(this, _BaseDataService_queryCacheUnsubscribe, __classPrivateFieldGet(this, _BaseDataService_queryClient, "f")
|
|
87
76
|
.getQueryCache()
|
|
88
77
|
.subscribe((event) => {
|
|
89
|
-
log('Query cache event emitted', event);
|
|
90
78
|
if (['added', 'updated', 'removed'].includes(event.type)) {
|
|
91
|
-
__classPrivateFieldGet(this, _BaseDataService_instances, "m", _BaseDataService_publishCacheUpdate).call(this,
|
|
92
|
-
__classPrivateFieldGet(this, _BaseDataService_debouncedPersist, "f")?.call(this);
|
|
93
|
-
}
|
|
94
|
-
}), "f");
|
|
95
|
-
log('Subscribing to mutation cache');
|
|
96
|
-
__classPrivateFieldSet(this, _BaseDataService_mutationCacheUnsubscribe, __classPrivateFieldGet(this, _BaseDataService_queryClient, "f")
|
|
97
|
-
.getMutationCache()
|
|
98
|
-
.subscribe((event) => {
|
|
99
|
-
log('Mutation cache event emitted', event);
|
|
100
|
-
if (['added', 'updated', 'removed'].includes(event.type) &&
|
|
101
|
-
event.mutation?.options.mutationKey !== undefined) {
|
|
102
|
-
const mutationHash = (0, query_core_1.hashKey)(event.mutation.options.mutationKey);
|
|
103
|
-
__classPrivateFieldGet(this, _BaseDataService_instances, "m", _BaseDataService_publishCacheUpdate).call(this, 'mutation', event.type, mutationHash);
|
|
79
|
+
__classPrivateFieldGet(this, _BaseDataService_instances, "m", _BaseDataService_publishCacheUpdate).call(this, event.query.queryHash, event.type);
|
|
104
80
|
__classPrivateFieldGet(this, _BaseDataService_debouncedPersist, "f")?.call(this);
|
|
105
81
|
}
|
|
106
82
|
}), "f");
|
|
@@ -111,15 +87,14 @@ class BaseDataService {
|
|
|
111
87
|
*
|
|
112
88
|
* @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.
|
|
113
89
|
* Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
|
|
114
|
-
* @param options.queryFn - The query function.
|
|
115
90
|
* @param options.responseStruct - An optional struct for validating the response of the query function.
|
|
116
91
|
* @returns The query results.
|
|
117
92
|
*/
|
|
118
|
-
async fetchQuery({
|
|
93
|
+
async fetchQuery({ responseStruct, ...options }) {
|
|
119
94
|
return __classPrivateFieldGet(this, _BaseDataService_queryClient, "f").fetchQuery({
|
|
120
95
|
...options,
|
|
121
96
|
queryFn: async (context) => {
|
|
122
|
-
const response = await __classPrivateFieldGet(this, _BaseDataService_policy, "f").execute(() => queryFn(context));
|
|
97
|
+
const response = await __classPrivateFieldGet(this, _BaseDataService_policy, "f").execute(() => options.queryFn(context));
|
|
123
98
|
return (0, utils_js_1.processQueryResponse)(options.queryKey, response, responseStruct);
|
|
124
99
|
},
|
|
125
100
|
});
|
|
@@ -159,43 +134,6 @@ class BaseDataService {
|
|
|
159
134
|
const pageIndex = result.pageParams.findIndex((param) => (0, fast_deep_equal_1.default)(param, pageParam));
|
|
160
135
|
return result.pages[pageIndex];
|
|
161
136
|
}
|
|
162
|
-
/**
|
|
163
|
-
* Execute a mutation (e.g. a request that is expected to change server-side data).
|
|
164
|
-
* Unlike `fetchQuery`, the request will not be cached or retried.
|
|
165
|
-
*
|
|
166
|
-
* @param options - The options defining the mutation. Keep in mind that `mutationKey` and `mutationFn` are required when using data services.
|
|
167
|
-
* Additionally, `retry` and `retryDelay` are not available.
|
|
168
|
-
* @param options.mutationFn - The mutation function.
|
|
169
|
-
* @param options.responseStruct - An optional struct for validating the response of the mutation function.
|
|
170
|
-
* @param options.globalId - A string which uniquely identifies this mutation
|
|
171
|
-
* across different query clients — specifically, the one in this data service
|
|
172
|
-
* and the one that `createUIQueryClient` in `@metamask/react-data-query`
|
|
173
|
-
* holds (in fact usually you don't need to pass this — `createUIQueryClient`
|
|
174
|
-
* will do it automatically). This global ID will be stored in the new
|
|
175
|
-
* mutation `meta` data and included in `:cacheUpdated` payloads.
|
|
176
|
-
* @returns The mutation results.
|
|
177
|
-
*/
|
|
178
|
-
async executeMutation({ mutationFn, responseStruct, globalId, ...options }) {
|
|
179
|
-
const mutationCache = __classPrivateFieldGet(this, _BaseDataService_queryClient, "f").getMutationCache();
|
|
180
|
-
const mutation = mutationCache.build(__classPrivateFieldGet(this, _BaseDataService_queryClient, "f"), {
|
|
181
|
-
...options,
|
|
182
|
-
...(globalId !== undefined && {
|
|
183
|
-
meta: { ...options.meta, globalId },
|
|
184
|
-
}),
|
|
185
|
-
mutationFn: async (...args) => {
|
|
186
|
-
// To guard against mutations being retried, we deliberately execute the
|
|
187
|
-
// mutation function through the circuit breaker policy alone, rather
|
|
188
|
-
// than through `this.#policy` (which is a combination of both a
|
|
189
|
-
// circuit breaker policy and retry policy).
|
|
190
|
-
const response = await __classPrivateFieldGet(this, _BaseDataService_policy, "f").circuitBreakerPolicy.execute(() => mutationFn(...args));
|
|
191
|
-
return (0, utils_js_1.processMutationResponse)(options.mutationKey, response, responseStruct);
|
|
192
|
-
},
|
|
193
|
-
});
|
|
194
|
-
// We purposely pass an empty set of variables because this method is
|
|
195
|
-
// intended to be used internally by the data service, not end users, and
|
|
196
|
-
// the data service has full control of `mutationFn` anyway.
|
|
197
|
-
return await mutation.execute({});
|
|
198
|
-
}
|
|
199
137
|
/**
|
|
200
138
|
* Invalidate queries serviced by this data service.
|
|
201
139
|
*
|
|
@@ -221,38 +159,25 @@ class BaseDataService {
|
|
|
221
159
|
destroy() {
|
|
222
160
|
__classPrivateFieldGet(this, _BaseDataService_debouncedPersist, "f")?.cancel();
|
|
223
161
|
__classPrivateFieldGet(this, _BaseDataService_queryCacheUnsubscribe, "f").call(this);
|
|
224
|
-
__classPrivateFieldGet(this, _BaseDataService_mutationCacheUnsubscribe, "f").call(this);
|
|
225
|
-
// `QueryClient.clear()` clears both caches, but `MutationCache.clear()`
|
|
226
|
-
// only drops its references to mutations without clearing their pending
|
|
227
|
-
// garbage-collection timers. We destroy each mutation first so those timers
|
|
228
|
-
// are cleared and do not keep the process alive.
|
|
229
|
-
for (const mutation of __classPrivateFieldGet(this, _BaseDataService_queryClient, "f").getMutationCache().getAll()) {
|
|
230
|
-
mutation.destroy();
|
|
231
|
-
}
|
|
232
162
|
__classPrivateFieldGet(this, _BaseDataService_queryClient, "f").clear();
|
|
233
163
|
this.messenger.clearSubscriptions();
|
|
234
164
|
this.messenger.clearActions();
|
|
235
165
|
}
|
|
236
166
|
}
|
|
237
167
|
exports.BaseDataService = BaseDataService;
|
|
238
|
-
_BaseDataService_messenger = new WeakMap(), _BaseDataService_externalMessenger = new WeakMap(), _BaseDataService_policy = new WeakMap(), _BaseDataService_queryClient = new WeakMap(), _BaseDataService_queryCacheUnsubscribe = new WeakMap(),
|
|
239
|
-
const state =
|
|
168
|
+
_BaseDataService_messenger = new WeakMap(), _BaseDataService_externalMessenger = new WeakMap(), _BaseDataService_policy = new WeakMap(), _BaseDataService_queryClient = new WeakMap(), _BaseDataService_queryCacheUnsubscribe = new WeakMap(), _BaseDataService_debouncedPersist = new WeakMap(), _BaseDataService_persistenceConfig = new WeakMap(), _BaseDataService_instances = new WeakSet(), _BaseDataService_publishCacheUpdate = function _BaseDataService_publishCacheUpdate(hash, type) {
|
|
169
|
+
const state = type === 'added' || type === 'updated'
|
|
240
170
|
? (0, query_core_1.dehydrate)(__classPrivateFieldGet(this, _BaseDataService_queryClient, "f"), {
|
|
241
|
-
shouldDehydrateQuery: (query) =>
|
|
242
|
-
shouldDehydrateMutation: (mutation) => objectType === 'mutation' &&
|
|
243
|
-
mutation.options.mutationKey !== undefined &&
|
|
244
|
-
(0, query_core_1.hashKey)(mutation.options.mutationKey) === hash,
|
|
171
|
+
shouldDehydrateQuery: (query) => query.queryHash === hash,
|
|
245
172
|
})
|
|
246
173
|
: null;
|
|
247
174
|
__classPrivateFieldGet(this, _BaseDataService_messenger, "f").publish(`${this.name}:cacheUpdated`, {
|
|
248
|
-
type
|
|
249
|
-
objectType,
|
|
175
|
+
type,
|
|
250
176
|
hash,
|
|
251
177
|
state,
|
|
252
178
|
});
|
|
253
179
|
__classPrivateFieldGet(this, _BaseDataService_messenger, "f").publish(`${this.name}:cacheUpdated:${hash}`, {
|
|
254
|
-
type
|
|
255
|
-
objectType,
|
|
180
|
+
type,
|
|
256
181
|
state,
|
|
257
182
|
});
|
|
258
183
|
}, _BaseDataService_persistCache =
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseDataService.cjs","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,mDAM6B;AAM7B,uDAA+C;AAC/C,2CAA2D;AAE3D,qDAmB8B;AAC9B,sEAAwC;AACxC,mCAAiD;AAEjD,sEAIkC;AAClC,8CAAiE;AACjE,0CAA2E;AAE3E,MAAM,GAAG,GAAG,IAAA,+BAAkB,EAAC,0BAAa,EAAE,iBAAiB,CAAC,CAAC;AAmFjE;;GAEG;AACH,MAAM,qBAAqB,GAAmB;IAC5C,OAAO,EAAE;QACP,KAAK,EAAE,KAAK;QACZ,SAAS,EAAE,IAAA,sBAAc,EAAC,CAAC,EAAE,gBAAQ,CAAC,MAAM,CAAC;KAC9C;IACD,SAAS,EAAE;QACT,KAAK,EAAE,KAAK;KACb;CACF,CAAC;AAEW,QAAA,mBAAmB,GAAG,OAAO,CAAC;AA2B3C,MAAa,eAAe;IA+B1B,YAAY,EACV,IAAI,EACJ,SAAS,EACT,iBAAiB,GAAG,EAAE,EACtB,aAAa,EACb,iBAAiB,GAalB;;QA3CQ,6CAIP;QAEO,qDAGP;QAIO,0CAAuB;QAEvB,+CAA0B;QAE1B,yDAAmC;QAEnC,4DAAsC;QAEtC,oDAA8C;QAE9C,qDAA8C;QAqBrD,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QAEjB,2E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AAmB,CAAC,IAAI,CAChC,2BAA2B,EAC3B,IAAI,CAAC,IAAI,EACT,2BAAmB,CACpB,CAAC;QACF,OAAO;IACT,CAAC;IAED,IAAA,oBAAO,EAAC,uBAAA,IAAI,oCAAa,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;AAC1C,CAAC","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 MutationOptions,\n OmitKeyof,\n QueryClient,\n QueryClientConfig,\n QueryFunction,\n WithRequired,\n dehydrate,\n hydrate,\n hashKey,\n MutationFunction,\n} from '@tanstack/query-core';\nimport deepEqual from 'fast-deep-equal';\nimport { debounce, DebouncedFunc } from 'lodash';\n\nimport {\n createServicePolicy,\n CreateServicePolicyOptions,\n ServicePolicy,\n} from './createServicePolicy.js';\nimport { createModuleLogger, projectLogger } from './loggers.js';\nimport { processMutationResponse, processQueryResponse } from './utils.js';\n\nconst log = createModuleLogger(projectLogger, 'BaseDataService');\n\n/**\n * Data service mutations and queries use the following format:\n * `['${ServiceName}:${ActionName}', ...params]`\n */\ntype Key = [string, ...Json[]] | readonly [string, ...Json[]];\n\n/*\n * Data service queries use the following format:\n * `['${ServiceName}:${ActionName}', ...params]`\n */\nexport type QueryKey = Key;\n\n/*\n * Data service mutations use the following format:\n * `['${ServiceName}:${ActionName}', ...params]`\n */\nexport type MutationKey = Key;\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 objectType: 'query' | 'mutation';\n} & (\n | { type: 'added' | 'updated'; state: DehydratedState }\n | {\n type: 'removed';\n state: null;\n }\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/*\n * Defaults to apply to all data service queries if no default option specified.\n */\nconst QUERY_CLIENT_DEFAULTS: DefaultOptions = {\n queries: {\n retry: false,\n staleTime: inMilliseconds(1, Duration.Minute),\n },\n mutations: {\n retry: false,\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 #mutationCacheUnsubscribe: () => 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: {\n ...QUERY_CLIENT_DEFAULTS.mutations,\n ...queryClientConfig.defaultOptions?.mutations,\n },\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 log('Query cache event emitted', event);\n if (['added', 'updated', 'removed'].includes(event.type)) {\n this.#publishCacheUpdate(\n 'query',\n event.type as CacheUpdatedType,\n event.query.queryHash,\n );\n\n this.#debouncedPersist?.();\n }\n });\n\n log('Subscribing to mutation cache');\n this.#mutationCacheUnsubscribe = this.#queryClient\n .getMutationCache()\n .subscribe((event) => {\n log('Mutation cache event emitted', event);\n if (\n ['added', 'updated', 'removed'].includes(event.type) &&\n event.mutation?.options.mutationKey !== undefined\n ) {\n const mutationHash = hashKey(event.mutation.options.mutationKey);\n this.#publishCacheUpdate(\n 'mutation',\n event.type as CacheUpdatedType,\n mutationHash,\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.queryFn - The query function.\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 queryFn,\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(() => queryFn(context));\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 * Execute a mutation (e.g. a request that is expected to change server-side data).\n * Unlike `fetchQuery`, the request will not be cached or retried.\n *\n * @param options - The options defining the mutation. Keep in mind that `mutationKey` and `mutationFn` are required when using data services.\n * Additionally, `retry` and `retryDelay` are not available.\n * @param options.mutationFn - The mutation function.\n * @param options.responseStruct - An optional struct for validating the response of the mutation function.\n * @param options.globalId - A string which uniquely identifies this mutation\n * across different query clients — specifically, the one in this data service\n * and the one that `createUIQueryClient` in `@metamask/react-data-query`\n * holds (in fact usually you don't need to pass this — `createUIQueryClient`\n * will do it automatically). This global ID will be stored in the new\n * mutation `meta` data and included in `:cacheUpdated` payloads.\n * @returns The mutation results.\n */\n protected async executeMutation<\n TMutationFnData extends Json,\n // We have to use `Struct<any>` here, as using `Struct<InputResponse>` (or\n // even `Struct<unknown>`) would reject a more concrete, \"real world\" struct.\n // The reason is that `Struct` is an object type with methods whose signatures\n // feature the struct's content type, making `Struct` contravariant in its\n // content type. The only way to get around this is to use `any`.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TDataStruct extends Struct<any> | undefined = undefined,\n TData = TDataStruct extends Struct<infer StructType>\n ? StructType\n : TMutationFnData,\n TError = DefaultError,\n TOnMutateResult = unknown,\n TMutationKey extends MutationKey = MutationKey,\n >({\n mutationFn,\n responseStruct,\n globalId,\n ...options\n }: OmitKeyof<\n MutationOptions<TData, TError, Record<never, never>, TOnMutateResult>,\n 'retry' | 'retryDelay' | 'mutationKey' | 'mutationFn'\n > & {\n mutationKey: TMutationKey;\n mutationFn: MutationFunction<TMutationFnData, Record<never, never>>;\n responseStruct?: TDataStruct;\n globalId?: string;\n }): Promise<TData> {\n const mutationCache = this.#queryClient.getMutationCache();\n const mutation = mutationCache.build<\n TData,\n TError,\n Record<never, never>,\n TOnMutateResult\n >(this.#queryClient, {\n ...options,\n ...(globalId !== undefined && {\n meta: { ...options.meta, globalId },\n }),\n mutationFn: async (...args) => {\n // To guard against mutations being retried, we deliberately execute the\n // mutation function through the circuit breaker policy alone, rather\n // than through `this.#policy` (which is a combination of both a\n // circuit breaker policy and retry policy).\n const response = await this.#policy.circuitBreakerPolicy.execute(() =>\n mutationFn(...args),\n );\n return processMutationResponse(\n options.mutationKey,\n response,\n responseStruct,\n );\n },\n });\n // We purposely pass an empty set of variables because this method is\n // intended to be used internally by the data service, not end users, and\n // the data service has full control of `mutationFn` anyway.\n return await mutation.execute({});\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.#mutationCacheUnsubscribe();\n // `QueryClient.clear()` clears both caches, but `MutationCache.clear()`\n // only drops its references to mutations without clearing their pending\n // garbage-collection timers. We destroy each mutation first so those timers\n // are cleared and do not keep the process alive.\n for (const mutation of this.#queryClient.getMutationCache().getAll()) {\n mutation.destroy();\n }\n this.#queryClient.clear();\n this.messenger.clearSubscriptions();\n this.messenger.clearActions();\n }\n\n /**\n * Publish `cacheUpdated` events when the query or mutation cache is updated.\n *\n * @param objectType - The type of object updated (\"query\" or \"mutation\").\n * @param eventType - What happened to the query or mutation (\"added\" or \"updated\").\n * @param hash - The hash of the query or mutation.\n */\n #publishCacheUpdate(\n objectType: 'query' | 'mutation',\n eventType: CacheUpdatedType,\n hash: string,\n ): void {\n const state =\n eventType === 'added' || eventType === 'updated'\n ? dehydrate(this.#queryClient, {\n shouldDehydrateQuery: (query) =>\n objectType === 'query' && query.queryHash === hash,\n shouldDehydrateMutation: (mutation) =>\n objectType === 'mutation' &&\n mutation.options.mutationKey !== undefined &&\n hashKey(mutation.options.mutationKey) === hash,\n })\n : null;\n\n this.#messenger.publish(\n `${this.name}:cacheUpdated` as const,\n {\n type: eventType,\n objectType,\n hash,\n state,\n } as DataServiceCacheUpdatedPayload,\n );\n this.#messenger.publish(\n `${this.name}:cacheUpdated:${hash}` as const,\n {\n type: eventType,\n objectType,\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
|
+
{"version":3,"file":"BaseDataService.cjs","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,mDAM6B;AAM7B,uDAA+C;AAC/C,2CAA2D;AAE3D,qDAgB8B;AAC9B,sEAAwC;AACxC,mCAAiD;AAEjD,sEAIkC;AAClC,0CAAkD;AAiElD,+EAA+E;AAC/E,MAAM,qBAAqB,GAAmB;IAC5C,OAAO,EAAE;QACP,KAAK,EAAE,KAAK;QACZ,SAAS,EAAE,IAAA,sBAAc,EAAC,CAAC,EAAE,gBAAQ,CAAC,MAAM,CAAC;KAC9C;CACF,CAAC;AAEW,QAAA,mBAAmB,GAAG,OAAO,CAAC;AA2B3C,MAAa,eAAe;IA6B1B,YAAY,EACV,IAAI,EACJ,SAAS,EACT,iBAAiB,GAAG,EAAE,EACtB,aAAa,EACb,iBAAiB,GAalB;;QAzCQ,6CAIP;QAEO,qDAGP;QAIO,0CAAuB;QAEvB,+CAA0B;QAE1B,yDAAmC;QAEnC,oDA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IAAI,CACjE,wBAAwB,EACxB,IAAI,CAAC,IAAI,EACT,2BAAmB,CACpB,CAAC;IAEF,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,OAAO;IACT,CAAC;IAED,MAAM,KAAK,GAAG,YAAyC,CAAC;IAExD,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,SAAS,IAAI,uBAAA,IAAI,0CAAmB,CAAC,MAAM,EAAE,CAAC;QACnE,MAAM,uBAAA,IAAI,0CAAmB,CAAC,IAAI,CAChC,2BAA2B,EAC3B,IAAI,CAAC,IAAI,EACT,2BAAmB,CACpB,CAAC;QACF,OAAO;IACT,CAAC;IAED,IAAA,oBAAO,EAAC,uBAAA,IAAI,oCAAa,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;AAC1C,CAAC","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';\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[]];\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"]}
|
|
@@ -2,15 +2,9 @@ import { Messenger, ActionConstraint, EventConstraint, MessengerActions, Messeng
|
|
|
2
2
|
import type { StorageServiceGetItemAction, StorageServiceRemoveItemAction, StorageServiceSetItemAction } from "@metamask/storage-service";
|
|
3
3
|
import { Struct } from "@metamask/superstruct";
|
|
4
4
|
import type { Json } from "@metamask/utils";
|
|
5
|
-
import { DefaultError, DehydratedState, FetchQueryOptions, InfiniteData, InfiniteQueryPageParamsOptions, InvalidateOptions, InvalidateQueryFilters,
|
|
5
|
+
import { DefaultError, DehydratedState, FetchQueryOptions, InfiniteData, InfiniteQueryPageParamsOptions, InvalidateOptions, InvalidateQueryFilters, OmitKeyof, QueryClientConfig, QueryFunction, WithRequired } from "@tanstack/query-core";
|
|
6
6
|
import { CreateServicePolicyOptions } from "./createServicePolicy.cjs";
|
|
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;
|
|
7
|
+
export type QueryKey = [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
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseDataService.d.cts","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,gBAAgB,EAChB,eAAe,EACf,gBAAgB,EAChB,eAAe,EAChB,4BAA4B;AAC7B,OAAO,KAAK,EACV,2BAA2B,EAC3B,8BAA8B,EAC9B,2BAA2B,EAC5B,kCAAkC;AACnC,OAAO,EAAE,MAAM,EAAE,8BAA8B;AAE/C,OAAO,KAAK,EAAE,IAAI,EAAE,wBAAwB;AAC5C,OAAO,EACL,YAAY,EAEZ,eAAe,EACf,iBAAiB,EACjB,YAAY,EACZ,8BAA8B,EAC9B,iBAAiB,EACjB,sBAAsB,EACtB,
|
|
1
|
+
{"version":3,"file":"BaseDataService.d.cts","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,gBAAgB,EAChB,eAAe,EACf,gBAAgB,EAChB,eAAe,EAChB,4BAA4B;AAC7B,OAAO,KAAK,EACV,2BAA2B,EAC3B,8BAA8B,EAC9B,2BAA2B,EAC5B,kCAAkC;AACnC,OAAO,EAAE,MAAM,EAAE,8BAA8B;AAE/C,OAAO,KAAK,EAAE,IAAI,EAAE,wBAAwB;AAC5C,OAAO,EACL,YAAY,EAEZ,eAAe,EACf,iBAAiB,EACjB,YAAY,EACZ,8BAA8B,EAC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WAAW,CAAC;KAC9B,EACH,SAAS,CAAC,EAAE,UAAU,GACrB,OAAO,CAAC,KAAK,CAAC;IAuDjB;;;;;;OAMG;IACG,iBAAiB,CACrB,OAAO,CAAC,EAAE,sBAAsB,CAAC,QAAQ,CAAC,EAC1C,OAAO,CAAC,EAAE,iBAAiB,GAC1B,OAAO,CAAC,IAAI,CAAC;IAIhB;;OAEG;IACH,IAAI,IAAI,IAAI;IAOZ;;;OAGG;IACH,OAAO,IAAI,IAAI;CA2GhB"}
|
|
@@ -2,15 +2,9 @@ import { Messenger, ActionConstraint, EventConstraint, MessengerActions, Messeng
|
|
|
2
2
|
import type { StorageServiceGetItemAction, StorageServiceRemoveItemAction, StorageServiceSetItemAction } from "@metamask/storage-service";
|
|
3
3
|
import { Struct } from "@metamask/superstruct";
|
|
4
4
|
import type { Json } from "@metamask/utils";
|
|
5
|
-
import { DefaultError, DehydratedState, FetchQueryOptions, InfiniteData, InfiniteQueryPageParamsOptions, InvalidateOptions, InvalidateQueryFilters,
|
|
5
|
+
import { DefaultError, DehydratedState, FetchQueryOptions, InfiniteData, InfiniteQueryPageParamsOptions, InvalidateOptions, InvalidateQueryFilters, OmitKeyof, QueryClientConfig, QueryFunction, WithRequired } from "@tanstack/query-core";
|
|
6
6
|
import { CreateServicePolicyOptions } from "./createServicePolicy.mjs";
|
|
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;
|
|
7
|
+
export type QueryKey = [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
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseDataService.d.mts","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,gBAAgB,EAChB,eAAe,EACf,gBAAgB,EAChB,eAAe,EAChB,4BAA4B;AAC7B,OAAO,KAAK,EACV,2BAA2B,EAC3B,8BAA8B,EAC9B,2BAA2B,EAC5B,kCAAkC;AACnC,OAAO,EAAE,MAAM,EAAE,8BAA8B;AAE/C,OAAO,KAAK,EAAE,IAAI,EAAE,wBAAwB;AAC5C,OAAO,EACL,YAAY,EAEZ,eAAe,EACf,iBAAiB,EACjB,YAAY,EACZ,8BAA8B,EAC9B,iBAAiB,EACjB,sBAAsB,EACtB,
|
|
1
|
+
{"version":3,"file":"BaseDataService.d.mts","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,gBAAgB,EAChB,eAAe,EACf,gBAAgB,EAChB,eAAe,EAChB,4BAA4B;AAC7B,OAAO,KAAK,EACV,2BAA2B,EAC3B,8BAA8B,EAC9B,2BAA2B,EAC5B,kCAAkC;AACnC,OAAO,EAAE,MAAM,EAAE,8BAA8B;AAE/C,OAAO,KAAK,EAAE,IAAI,EAAE,wBAAwB;AAC5C,OAAO,EACL,YAAY,EAEZ,eAAe,EACf,iBAAiB,EACjB,YAAY,EACZ,8BAA8B,EAC9B,iBAAiB,EACjB,sBAAsB,EACtB,SAAS,EAET,iBAAiB,EACjB,aAAa,EACb,YAAY,EAGb,6BAA6B;AAI9B,OAAO,EAEL,0BAA0B,EAE3B,kCAAiC;AAIlC,MAAM,MAAM,QAAQ,GAAG,CAAC,MAAM,EAAE,GAAG,IAAI,EAAE,CAAC,CAAC;AAE3C;;;;;GAKG;AACH,MAAM,MAAM,aAAa,CAAC,SAAS,SAAS,MAAM,IAAI,SAAS,CAC7D,SAAS,EACT,gBAAgB,EAChB,eAAe,EAIf,GAAG,CACJ,CAAC;AAEF,MAAM,M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var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
9
9
|
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
10
10
|
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
11
11
|
};
|
|
12
|
-
var _BaseDataService_instances, _BaseDataService_messenger, _BaseDataService_externalMessenger, _BaseDataService_policy, _BaseDataService_queryClient, _BaseDataService_queryCacheUnsubscribe,
|
|
12
|
+
var _BaseDataService_instances, _BaseDataService_messenger, _BaseDataService_externalMessenger, _BaseDataService_policy, _BaseDataService_queryClient, _BaseDataService_queryCacheUnsubscribe, _BaseDataService_debouncedPersist, _BaseDataService_persistenceConfig, _BaseDataService_publishCacheUpdate, _BaseDataService_persistCache, _BaseDataService_loadCache;
|
|
13
13
|
function $importDefault(module) {
|
|
14
14
|
if (module?.__esModule) {
|
|
15
15
|
return module.default;
|
|
@@ -19,26 +19,19 @@ function $importDefault(module) {
|
|
|
19
19
|
import { Messenger } from "@metamask/messenger";
|
|
20
20
|
import { Struct } from "@metamask/superstruct";
|
|
21
21
|
import { Duration, inMilliseconds } from "@metamask/utils";
|
|
22
|
-
import { QueryClient, dehydrate, hydrate
|
|
22
|
+
import { QueryClient, dehydrate, hydrate } from "@tanstack/query-core";
|
|
23
23
|
import $deepEqual from "fast-deep-equal";
|
|
24
24
|
const deepEqual = $importDefault($deepEqual);
|
|
25
25
|
import $lodash from "lodash";
|
|
26
26
|
const { debounce } = $lodash;
|
|
27
27
|
import { createServicePolicy } from "./createServicePolicy.mjs";
|
|
28
|
-
import {
|
|
29
|
-
|
|
30
|
-
const log = createModuleLogger(projectLogger, 'BaseDataService');
|
|
31
|
-
/*
|
|
32
|
-
* Defaults to apply to all data service queries if no default option specified.
|
|
33
|
-
*/
|
|
28
|
+
import { processQueryResponse } from "./utils.mjs";
|
|
29
|
+
// Defaults to apply to all data service queries if no default option specified
|
|
34
30
|
const QUERY_CLIENT_DEFAULTS = {
|
|
35
31
|
queries: {
|
|
36
32
|
retry: false,
|
|
37
33
|
staleTime: inMilliseconds(1, Duration.Minute),
|
|
38
34
|
},
|
|
39
|
-
mutations: {
|
|
40
|
-
retry: false,
|
|
41
|
-
},
|
|
42
35
|
};
|
|
43
36
|
export const STORAGE_SERVICE_KEY = 'cache';
|
|
44
37
|
export class BaseDataService {
|
|
@@ -49,7 +42,6 @@ export class BaseDataService {
|
|
|
49
42
|
_BaseDataService_policy.set(this, void 0);
|
|
50
43
|
_BaseDataService_queryClient.set(this, void 0);
|
|
51
44
|
_BaseDataService_queryCacheUnsubscribe.set(this, void 0);
|
|
52
|
-
_BaseDataService_mutationCacheUnsubscribe.set(this, void 0);
|
|
53
45
|
_BaseDataService_debouncedPersist.set(this, void 0);
|
|
54
46
|
_BaseDataService_persistenceConfig.set(this, void 0);
|
|
55
47
|
this.name = name;
|
|
@@ -67,10 +59,7 @@ export class BaseDataService {
|
|
|
67
59
|
...QUERY_CLIENT_DEFAULTS.queries,
|
|
68
60
|
...queryClientConfig.defaultOptions?.queries,
|
|
69
61
|
},
|
|
70
|
-
mutations:
|
|
71
|
-
...QUERY_CLIENT_DEFAULTS.mutations,
|
|
72
|
-
...queryClientConfig.defaultOptions?.mutations,
|
|
73
|
-
},
|
|
62
|
+
mutations: queryClientConfig.defaultOptions?.mutations,
|
|
74
63
|
},
|
|
75
64
|
}), "f");
|
|
76
65
|
__classPrivateFieldSet(this, _BaseDataService_persistenceConfig, persistenceConfig, "f");
|
|
@@ -88,21 +77,8 @@ export class BaseDataService {
|
|
|
88
77
|
__classPrivateFieldSet(this, _BaseDataService_queryCacheUnsubscribe, __classPrivateFieldGet(this, _BaseDataService_queryClient, "f")
|
|
89
78
|
.getQueryCache()
|
|
90
79
|
.subscribe((event) => {
|
|
91
|
-
log('Query cache event emitted', event);
|
|
92
80
|
if (['added', 'updated', 'removed'].includes(event.type)) {
|
|
93
|
-
__classPrivateFieldGet(this, _BaseDataService_instances, "m", _BaseDataService_publishCacheUpdate).call(this,
|
|
94
|
-
__classPrivateFieldGet(this, _BaseDataService_debouncedPersist, "f")?.call(this);
|
|
95
|
-
}
|
|
96
|
-
}), "f");
|
|
97
|
-
log('Subscribing to mutation cache');
|
|
98
|
-
__classPrivateFieldSet(this, _BaseDataService_mutationCacheUnsubscribe, __classPrivateFieldGet(this, _BaseDataService_queryClient, "f")
|
|
99
|
-
.getMutationCache()
|
|
100
|
-
.subscribe((event) => {
|
|
101
|
-
log('Mutation cache event emitted', event);
|
|
102
|
-
if (['added', 'updated', 'removed'].includes(event.type) &&
|
|
103
|
-
event.mutation?.options.mutationKey !== undefined) {
|
|
104
|
-
const mutationHash = hashKey(event.mutation.options.mutationKey);
|
|
105
|
-
__classPrivateFieldGet(this, _BaseDataService_instances, "m", _BaseDataService_publishCacheUpdate).call(this, 'mutation', event.type, mutationHash);
|
|
81
|
+
__classPrivateFieldGet(this, _BaseDataService_instances, "m", _BaseDataService_publishCacheUpdate).call(this, event.query.queryHash, event.type);
|
|
106
82
|
__classPrivateFieldGet(this, _BaseDataService_debouncedPersist, "f")?.call(this);
|
|
107
83
|
}
|
|
108
84
|
}), "f");
|
|
@@ -113,15 +89,14 @@ export class BaseDataService {
|
|
|
113
89
|
*
|
|
114
90
|
* @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.
|
|
115
91
|
* Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
|
|
116
|
-
* @param options.queryFn - The query function.
|
|
117
92
|
* @param options.responseStruct - An optional struct for validating the response of the query function.
|
|
118
93
|
* @returns The query results.
|
|
119
94
|
*/
|
|
120
|
-
async fetchQuery({
|
|
95
|
+
async fetchQuery({ responseStruct, ...options }) {
|
|
121
96
|
return __classPrivateFieldGet(this, _BaseDataService_queryClient, "f").fetchQuery({
|
|
122
97
|
...options,
|
|
123
98
|
queryFn: async (context) => {
|
|
124
|
-
const response = await __classPrivateFieldGet(this, _BaseDataService_policy, "f").execute(() => queryFn(context));
|
|
99
|
+
const response = await __classPrivateFieldGet(this, _BaseDataService_policy, "f").execute(() => options.queryFn(context));
|
|
125
100
|
return processQueryResponse(options.queryKey, response, responseStruct);
|
|
126
101
|
},
|
|
127
102
|
});
|
|
@@ -161,43 +136,6 @@ export class BaseDataService {
|
|
|
161
136
|
const pageIndex = result.pageParams.findIndex((param) => deepEqual(param, pageParam));
|
|
162
137
|
return result.pages[pageIndex];
|
|
163
138
|
}
|
|
164
|
-
/**
|
|
165
|
-
* Execute a mutation (e.g. a request that is expected to change server-side data).
|
|
166
|
-
* Unlike `fetchQuery`, the request will not be cached or retried.
|
|
167
|
-
*
|
|
168
|
-
* @param options - The options defining the mutation. Keep in mind that `mutationKey` and `mutationFn` are required when using data services.
|
|
169
|
-
* Additionally, `retry` and `retryDelay` are not available.
|
|
170
|
-
* @param options.mutationFn - The mutation function.
|
|
171
|
-
* @param options.responseStruct - An optional struct for validating the response of the mutation function.
|
|
172
|
-
* @param options.globalId - A string which uniquely identifies this mutation
|
|
173
|
-
* across different query clients — specifically, the one in this data service
|
|
174
|
-
* and the one that `createUIQueryClient` in `@metamask/react-data-query`
|
|
175
|
-
* holds (in fact usually you don't need to pass this — `createUIQueryClient`
|
|
176
|
-
* will do it automatically). This global ID will be stored in the new
|
|
177
|
-
* mutation `meta` data and included in `:cacheUpdated` payloads.
|
|
178
|
-
* @returns The mutation results.
|
|
179
|
-
*/
|
|
180
|
-
async executeMutation({ mutationFn, responseStruct, globalId, ...options }) {
|
|
181
|
-
const mutationCache = __classPrivateFieldGet(this, _BaseDataService_queryClient, "f").getMutationCache();
|
|
182
|
-
const mutation = mutationCache.build(__classPrivateFieldGet(this, _BaseDataService_queryClient, "f"), {
|
|
183
|
-
...options,
|
|
184
|
-
...(globalId !== undefined && {
|
|
185
|
-
meta: { ...options.meta, globalId },
|
|
186
|
-
}),
|
|
187
|
-
mutationFn: async (...args) => {
|
|
188
|
-
// To guard against mutations being retried, we deliberately execute the
|
|
189
|
-
// mutation function through the circuit breaker policy alone, rather
|
|
190
|
-
// than through `this.#policy` (which is a combination of both a
|
|
191
|
-
// circuit breaker policy and retry policy).
|
|
192
|
-
const response = await __classPrivateFieldGet(this, _BaseDataService_policy, "f").circuitBreakerPolicy.execute(() => mutationFn(...args));
|
|
193
|
-
return processMutationResponse(options.mutationKey, response, responseStruct);
|
|
194
|
-
},
|
|
195
|
-
});
|
|
196
|
-
// We purposely pass an empty set of variables because this method is
|
|
197
|
-
// intended to be used internally by the data service, not end users, and
|
|
198
|
-
// the data service has full control of `mutationFn` anyway.
|
|
199
|
-
return await mutation.execute({});
|
|
200
|
-
}
|
|
201
139
|
/**
|
|
202
140
|
* Invalidate queries serviced by this data service.
|
|
203
141
|
*
|
|
@@ -223,37 +161,24 @@ export class BaseDataService {
|
|
|
223
161
|
destroy() {
|
|
224
162
|
__classPrivateFieldGet(this, _BaseDataService_debouncedPersist, "f")?.cancel();
|
|
225
163
|
__classPrivateFieldGet(this, _BaseDataService_queryCacheUnsubscribe, "f").call(this);
|
|
226
|
-
__classPrivateFieldGet(this, _BaseDataService_mutationCacheUnsubscribe, "f").call(this);
|
|
227
|
-
// `QueryClient.clear()` clears both caches, but `MutationCache.clear()`
|
|
228
|
-
// only drops its references to mutations without clearing their pending
|
|
229
|
-
// garbage-collection timers. We destroy each mutation first so those timers
|
|
230
|
-
// are cleared and do not keep the process alive.
|
|
231
|
-
for (const mutation of __classPrivateFieldGet(this, _BaseDataService_queryClient, "f").getMutationCache().getAll()) {
|
|
232
|
-
mutation.destroy();
|
|
233
|
-
}
|
|
234
164
|
__classPrivateFieldGet(this, _BaseDataService_queryClient, "f").clear();
|
|
235
165
|
this.messenger.clearSubscriptions();
|
|
236
166
|
this.messenger.clearActions();
|
|
237
167
|
}
|
|
238
168
|
}
|
|
239
|
-
_BaseDataService_messenger = new WeakMap(), _BaseDataService_externalMessenger = new WeakMap(), _BaseDataService_policy = new WeakMap(), _BaseDataService_queryClient = new WeakMap(), _BaseDataService_queryCacheUnsubscribe = new WeakMap(),
|
|
240
|
-
const state =
|
|
169
|
+
_BaseDataService_messenger = new WeakMap(), _BaseDataService_externalMessenger = new WeakMap(), _BaseDataService_policy = new WeakMap(), _BaseDataService_queryClient = new WeakMap(), _BaseDataService_queryCacheUnsubscribe = new WeakMap(), _BaseDataService_debouncedPersist = new WeakMap(), _BaseDataService_persistenceConfig = new WeakMap(), _BaseDataService_instances = new WeakSet(), _BaseDataService_publishCacheUpdate = function _BaseDataService_publishCacheUpdate(hash, type) {
|
|
170
|
+
const state = type === 'added' || type === 'updated'
|
|
241
171
|
? dehydrate(__classPrivateFieldGet(this, _BaseDataService_queryClient, "f"), {
|
|
242
|
-
shouldDehydrateQuery: (query) =>
|
|
243
|
-
shouldDehydrateMutation: (mutation) => objectType === 'mutation' &&
|
|
244
|
-
mutation.options.mutationKey !== undefined &&
|
|
245
|
-
hashKey(mutation.options.mutationKey) === hash,
|
|
172
|
+
shouldDehydrateQuery: (query) => query.queryHash === hash,
|
|
246
173
|
})
|
|
247
174
|
: null;
|
|
248
175
|
__classPrivateFieldGet(this, _BaseDataService_messenger, "f").publish(`${this.name}:cacheUpdated`, {
|
|
249
|
-
type
|
|
250
|
-
objectType,
|
|
176
|
+
type,
|
|
251
177
|
hash,
|
|
252
178
|
state,
|
|
253
179
|
});
|
|
254
180
|
__classPrivateFieldGet(this, _BaseDataService_messenger, "f").publish(`${this.name}:cacheUpdated:${hash}`, {
|
|
255
|
-
type
|
|
256
|
-
objectType,
|
|
181
|
+
type,
|
|
257
182
|
state,
|
|
258
183
|
});
|
|
259
184
|
}, _BaseDataService_persistCache =
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseDataService.mjs","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,OAAO,EACL,SAAS,EAKV,4BAA4B;AAM7B,OAAO,EAAE,MAAM,EAAE,8BAA8B;AAC/C,OAAO,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,0CAAmB,CAAC,IAAI,CAChC,2BAA2B,EAC3B,IAAI,CAAC,IAAI,EACT,mBAAmB,CACpB,CAAC;QACF,OAAO;IACT,CAAC;IAED,MAAM,KAAK,GAAmB;QAC5B,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;QACrB,KAAK;KACN,CAAC;IAEF,MAAM,uBAAA,IAAI,0CAAmB,CAAC,IAAI,CAChC,wBAAwB,EACxB,IAAI,CAAC,IAAI,EACT,mBAAmB,EACnB,KAAwB,CACzB,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,KAAK;IACH,IAAI,CAAC,uBAAA,IAAI,0CAAmB,EAAE,CAAC;QAC7B,OAAO;IACT,CAAC;IAED,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,GAAG,MAAM,uBAAA,IAAI,0CAAmB,CAAC,IAAI,CACjE,wBAAwB,EACxB,IAAI,CAAC,IAAI,EACT,mBAAmB,CACpB,CAAC;IAEF,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,OAAO;IACT,CAAC;IAED,MAAM,KAAK,GAAG,YAAyC,CAAC;IAExD,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,SAAS,IAAI,uBAAA,IAAI,0CAAmB,CAAC,MAAM,EAAE,CAAC;QACnE,MAAM,uBAAA,IAAI,0CAAmB,CAAC,IAAI,CAChC,2BAA2B,EAC3B,IAAI,CAAC,IAAI,EACT,mBAAmB,CACpB,CAAC;QACF,OAAO;IACT,CAAC;IAED,OAAO,CAAC,uBAAA,IAAI,oCAAa,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;AAC1C,CAAC","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 MutationOptions,\n OmitKeyof,\n QueryClient,\n QueryClientConfig,\n QueryFunction,\n WithRequired,\n dehydrate,\n hydrate,\n hashKey,\n MutationFunction,\n} from '@tanstack/query-core';\nimport deepEqual from 'fast-deep-equal';\nimport { debounce, DebouncedFunc } from 'lodash';\n\nimport {\n createServicePolicy,\n CreateServicePolicyOptions,\n ServicePolicy,\n} from './createServicePolicy.js';\nimport { createModuleLogger, projectLogger } from './loggers.js';\nimport { processMutationResponse, processQueryResponse } from './utils.js';\n\nconst log = createModuleLogger(projectLogger, 'BaseDataService');\n\n/**\n * Data service mutations and queries use the following format:\n * `['${ServiceName}:${ActionName}', ...params]`\n */\ntype Key = [string, ...Json[]] | readonly [string, ...Json[]];\n\n/*\n * Data service queries use the following format:\n * `['${ServiceName}:${ActionName}', ...params]`\n */\nexport type QueryKey = Key;\n\n/*\n * Data service mutations use the following format:\n * `['${ServiceName}:${ActionName}', ...params]`\n */\nexport type MutationKey = Key;\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 objectType: 'query' | 'mutation';\n} & (\n | { type: 'added' | 'updated'; state: DehydratedState }\n | {\n type: 'removed';\n state: null;\n }\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/*\n * Defaults to apply to all data service queries if no default option specified.\n */\nconst QUERY_CLIENT_DEFAULTS: DefaultOptions = {\n queries: {\n retry: false,\n staleTime: inMilliseconds(1, Duration.Minute),\n },\n mutations: {\n retry: false,\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 #mutationCacheUnsubscribe: () => 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: {\n ...QUERY_CLIENT_DEFAULTS.mutations,\n ...queryClientConfig.defaultOptions?.mutations,\n },\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 log('Query cache event emitted', event);\n if (['added', 'updated', 'removed'].includes(event.type)) {\n this.#publishCacheUpdate(\n 'query',\n event.type as CacheUpdatedType,\n event.query.queryHash,\n );\n\n this.#debouncedPersist?.();\n }\n });\n\n log('Subscribing to mutation cache');\n this.#mutationCacheUnsubscribe = this.#queryClient\n .getMutationCache()\n .subscribe((event) => {\n log('Mutation cache event emitted', event);\n if (\n ['added', 'updated', 'removed'].includes(event.type) &&\n event.mutation?.options.mutationKey !== undefined\n ) {\n const mutationHash = hashKey(event.mutation.options.mutationKey);\n this.#publishCacheUpdate(\n 'mutation',\n event.type as CacheUpdatedType,\n mutationHash,\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.queryFn - The query function.\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 queryFn,\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(() => queryFn(context));\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 * Execute a mutation (e.g. a request that is expected to change server-side data).\n * Unlike `fetchQuery`, the request will not be cached or retried.\n *\n * @param options - The options defining the mutation. Keep in mind that `mutationKey` and `mutationFn` are required when using data services.\n * Additionally, `retry` and `retryDelay` are not available.\n * @param options.mutationFn - The mutation function.\n * @param options.responseStruct - An optional struct for validating the response of the mutation function.\n * @param options.globalId - A string which uniquely identifies this mutation\n * across different query clients — specifically, the one in this data service\n * and the one that `createUIQueryClient` in `@metamask/react-data-query`\n * holds (in fact usually you don't need to pass this — `createUIQueryClient`\n * will do it automatically). This global ID will be stored in the new\n * mutation `meta` data and included in `:cacheUpdated` payloads.\n * @returns The mutation results.\n */\n protected async executeMutation<\n TMutationFnData extends Json,\n // We have to use `Struct<any>` here, as using `Struct<InputResponse>` (or\n // even `Struct<unknown>`) would reject a more concrete, \"real world\" struct.\n // The reason is that `Struct` is an object type with methods whose signatures\n // feature the struct's content type, making `Struct` contravariant in its\n // content type. The only way to get around this is to use `any`.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TDataStruct extends Struct<any> | undefined = undefined,\n TData = TDataStruct extends Struct<infer StructType>\n ? StructType\n : TMutationFnData,\n TError = DefaultError,\n TOnMutateResult = unknown,\n TMutationKey extends MutationKey = MutationKey,\n >({\n mutationFn,\n responseStruct,\n globalId,\n ...options\n }: OmitKeyof<\n MutationOptions<TData, TError, Record<never, never>, TOnMutateResult>,\n 'retry' | 'retryDelay' | 'mutationKey' | 'mutationFn'\n > & {\n mutationKey: TMutationKey;\n mutationFn: MutationFunction<TMutationFnData, Record<never, never>>;\n responseStruct?: TDataStruct;\n globalId?: string;\n }): Promise<TData> {\n const mutationCache = this.#queryClient.getMutationCache();\n const mutation = mutationCache.build<\n TData,\n TError,\n Record<never, never>,\n TOnMutateResult\n >(this.#queryClient, {\n ...options,\n ...(globalId !== undefined && {\n meta: { ...options.meta, globalId },\n }),\n mutationFn: async (...args) => {\n // To guard against mutations being retried, we deliberately execute the\n // mutation function through the circuit breaker policy alone, rather\n // than through `this.#policy` (which is a combination of both a\n // circuit breaker policy and retry policy).\n const response = await this.#policy.circuitBreakerPolicy.execute(() =>\n mutationFn(...args),\n );\n return processMutationResponse(\n options.mutationKey,\n response,\n responseStruct,\n );\n },\n });\n // We purposely pass an empty set of variables because this method is\n // intended to be used internally by the data service, not end users, and\n // the data service has full control of `mutationFn` anyway.\n return await mutation.execute({});\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.#mutationCacheUnsubscribe();\n // `QueryClient.clear()` clears both caches, but `MutationCache.clear()`\n // only drops its references to mutations without clearing their pending\n // garbage-collection timers. We destroy each mutation first so those timers\n // are cleared and do not keep the process alive.\n for (const mutation of this.#queryClient.getMutationCache().getAll()) {\n mutation.destroy();\n }\n this.#queryClient.clear();\n this.messenger.clearSubscriptions();\n this.messenger.clearActions();\n }\n\n /**\n * Publish `cacheUpdated` events when the query or mutation cache is updated.\n *\n * @param objectType - The type of object updated (\"query\" or \"mutation\").\n * @param eventType - What happened to the query or mutation (\"added\" or \"updated\").\n * @param hash - The hash of the query or mutation.\n */\n #publishCacheUpdate(\n objectType: 'query' | 'mutation',\n eventType: CacheUpdatedType,\n hash: string,\n ): void {\n const state =\n eventType === 'added' || eventType === 'updated'\n ? dehydrate(this.#queryClient, {\n shouldDehydrateQuery: (query) =>\n objectType === 'query' && query.queryHash === hash,\n shouldDehydrateMutation: (mutation) =>\n objectType === 'mutation' &&\n mutation.options.mutationKey !== undefined &&\n hashKey(mutation.options.mutationKey) === hash,\n })\n : null;\n\n this.#messenger.publish(\n `${this.name}:cacheUpdated` as const,\n {\n type: eventType,\n objectType,\n hash,\n state,\n } as DataServiceCacheUpdatedPayload,\n );\n this.#messenger.publish(\n `${this.name}:cacheUpdated:${hash}` as const,\n {\n type: eventType,\n objectType,\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
|
+
{"version":3,"file":"BaseDataService.mjs","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,OAAO,EACL,SAAS,EAKV,4BAA4B;AAM7B,OAAO,EAAE,MAAM,EAAE,8BAA8B;AAC/C,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,wBAAwB;AAE3D,OAAO,EAUL,WAAW,EAIX,SAAS,EACT,OAAO,EACR,6BAA6B;AAC9B,OAAO,UAAS,wBAAwB;;;;AAGxC,OAAO,EACL,mBAAmB,EAGpB,kCAAiC;AAClC,OAAO,EAAE,oBAAoB,EAAE,oBAAmB;AAiElD,+EAA+E;AAC/E,MAAM,qBAAqB,GAAmB;IAC5C,OAAO,EAAE;QACP,KAAK,EAAE,KAAK;QACZ,SAAS,EAAE,cAAc,CAAC,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC;KAC9C;CACF,CAAC;AAEF,MAAM,CAAC,MAAM,mBAAmB,GAAG,OAAO,CAAC;AA2B3C,MAAM,OAAO,eAAe;IA6B1B,YAAY,EACV,IAAI,EACJ,SAAS,EACT,iBAAiB,GAAG,EAAE,EACtB,aAAa,EACb,iBAAiB,GAalB;;QAzCQ,6CAIP;QAEO,qDAGP;QAIO,0CAAuB;QAEvB,+CAA0B;QAE1B,yDAAmC;QAEnC,oDAA8C;QAE9C,qDAA8C;QAqBrD,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QAEjB,2EAA2E;QAC3E,kFAAkF;QAClF,yDAAyD;QACzD,6FAA6F;QAC7F,uBAAA,IAAI,8BAAc,SAIjB,MAAA,CAAC;QACF,uBAAA,IAAI,sCAAsB,SAGzB,MAAA,CAAC;QACF,IAAI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,IAAI,CAChC,2BAA2B,EAC3B,IAAI,CAAC,IAAI,EACT,mBAAmB,CACpB,CAAC;QACF,OAAO;IACT,CAAC;IAED,OAAO,CAAC,uBAAA,IAAI,oCAAa,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;AAC1C,CAAC","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';\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[]];\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"]}
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAKA,uCAQmB;AAPjB,+GAAA,kBAAkB,OAAA;AAClB,kHAAA,YAAY,OAAyB;AACrC,yGAAA,YAAY,OAAA;AACZ,4GAAA,eAAe,OAAA;AACf,+GAAA,kBAAkB,OAAA;AAClB,sGAAA,SAAS,OAAA;AACT,uGAAA,UAAU,OAAA;
|
|
1
|
+
{"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAKA,uCAQmB;AAPjB,+GAAA,kBAAkB,OAAA;AAClB,kHAAA,YAAY,OAAyB;AACrC,yGAAA,YAAY,OAAA;AACZ,4GAAA,eAAe,OAAA;AACf,+GAAA,kBAAkB,OAAA;AAClB,sGAAA,SAAS,OAAA;AACT,uGAAA,UAAU,OAAA;AAcZ,4DAAuD;AAA9C,qHAAA,eAAe,OAAA;AAExB,oEAMkC;AALhC,wIAAA,8BAA8B,OAAA;AAC9B,oIAAA,0BAA0B,OAAA;AAC1B,0IAAA,gCAAgC,OAAA;AAChC,6HAAA,mBAAmB,OAAA;AACnB,6HAAA,mBAAmB,OAAA","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/index.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export type { Event as CockatielEvent, FailureReason as CockatielFailureReason, } from "cockatiel";
|
|
2
2
|
export { BrokenCircuitError, EventEmitter as CockatielEventEmitter, CircuitState, ConstantBackoff, ExponentialBackoff, handleAll, handleWhen, } from "cockatiel";
|
|
3
|
-
export type { DataServiceActions, DataServiceEvents, DataServiceCacheUpdatedPayload, DataServiceGranularCacheUpdatedPayload, DataServiceInvalidateQueriesAction, DataServiceCacheUpdatedEvent, DataServiceGranularCacheUpdatedEvent, QueryKey,
|
|
3
|
+
export type { DataServiceActions, DataServiceEvents, DataServiceCacheUpdatedPayload, DataServiceGranularCacheUpdatedPayload, DataServiceInvalidateQueriesAction, DataServiceCacheUpdatedEvent, DataServiceGranularCacheUpdatedEvent, QueryKey, PersistenceConfiguration, } from "./BaseDataService.cjs";
|
|
4
4
|
export { BaseDataService } from "./BaseDataService.cjs";
|
|
5
5
|
export { DEFAULT_CIRCUIT_BREAK_DURATION, DEFAULT_DEGRADED_THRESHOLD, DEFAULT_MAX_CONSECUTIVE_FAILURES, DEFAULT_MAX_RETRIES, createServicePolicy, } from "./createServicePolicy.cjs";
|
|
6
6
|
export type { CreateServicePolicyOptions, ServicePolicy, } from "./createServicePolicy.cjs";
|
package/dist/index.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,KAAK,IAAI,cAAc,EACvB,aAAa,IAAI,sBAAsB,GACxC,kBAAkB;AAEnB,OAAO,EACL,kBAAkB,EAClB,YAAY,IAAI,qBAAqB,EACrC,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,SAAS,EACT,UAAU,GACX,kBAAkB;AAEnB,YAAY,EACV,kBAAkB,EAClB,iBAAiB,EACjB,8BAA8B,EAC9B,sCAAsC,EACtC,kCAAkC,EAClC,4BAA4B,EAC5B,oCAAoC,EACpC,QAAQ,EACR,
|
|
1
|
+
{"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,KAAK,IAAI,cAAc,EACvB,aAAa,IAAI,sBAAsB,GACxC,kBAAkB;AAEnB,OAAO,EACL,kBAAkB,EAClB,YAAY,IAAI,qBAAqB,EACrC,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,SAAS,EACT,UAAU,GACX,kBAAkB;AAEnB,YAAY,EACV,kBAAkB,EAClB,iBAAiB,EACjB,8BAA8B,EAC9B,sCAAsC,EACtC,kCAAkC,EAClC,4BAA4B,EAC5B,oCAAoC,EACpC,QAAQ,EACR,wBAAwB,GACzB,8BAA6B;AAC9B,OAAO,EAAE,eAAe,EAAE,8BAA6B;AAEvD,OAAO,EACL,8BAA8B,EAC9B,0BAA0B,EAC1B,gCAAgC,EAChC,mBAAmB,EACnB,mBAAmB,GACpB,kCAAiC;AAClC,YAAY,EACV,0BAA0B,EAC1B,aAAa,GACd,kCAAiC"}
|
package/dist/index.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export type { Event as CockatielEvent, FailureReason as CockatielFailureReason, } from "cockatiel";
|
|
2
2
|
export { BrokenCircuitError, EventEmitter as CockatielEventEmitter, CircuitState, ConstantBackoff, ExponentialBackoff, handleAll, handleWhen, } from "cockatiel";
|
|
3
|
-
export type { DataServiceActions, DataServiceEvents, DataServiceCacheUpdatedPayload, DataServiceGranularCacheUpdatedPayload, DataServiceInvalidateQueriesAction, DataServiceCacheUpdatedEvent, DataServiceGranularCacheUpdatedEvent, QueryKey,
|
|
3
|
+
export type { DataServiceActions, DataServiceEvents, DataServiceCacheUpdatedPayload, DataServiceGranularCacheUpdatedPayload, DataServiceInvalidateQueriesAction, DataServiceCacheUpdatedEvent, DataServiceGranularCacheUpdatedEvent, QueryKey, PersistenceConfiguration, } from "./BaseDataService.mjs";
|
|
4
4
|
export { BaseDataService } from "./BaseDataService.mjs";
|
|
5
5
|
export { DEFAULT_CIRCUIT_BREAK_DURATION, DEFAULT_DEGRADED_THRESHOLD, DEFAULT_MAX_CONSECUTIVE_FAILURES, DEFAULT_MAX_RETRIES, createServicePolicy, } from "./createServicePolicy.mjs";
|
|
6
6
|
export type { CreateServicePolicyOptions, ServicePolicy, } from "./createServicePolicy.mjs";
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,KAAK,IAAI,cAAc,EACvB,aAAa,IAAI,sBAAsB,GACxC,kBAAkB;AAEnB,OAAO,EACL,kBAAkB,EAClB,YAAY,IAAI,qBAAqB,EACrC,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,SAAS,EACT,UAAU,GACX,kBAAkB;AAEnB,YAAY,EACV,kBAAkB,EAClB,iBAAiB,EACjB,8BAA8B,EAC9B,sCAAsC,EACtC,kCAAkC,EAClC,4BAA4B,EAC5B,oCAAoC,EACpC,QAAQ,EACR,
|
|
1
|
+
{"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,KAAK,IAAI,cAAc,EACvB,aAAa,IAAI,sBAAsB,GACxC,kBAAkB;AAEnB,OAAO,EACL,kBAAkB,EAClB,YAAY,IAAI,qBAAqB,EACrC,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,SAAS,EACT,UAAU,GACX,kBAAkB;AAEnB,YAAY,EACV,kBAAkB,EAClB,iBAAiB,EACjB,8BAA8B,EAC9B,sCAAsC,EACtC,kCAAkC,EAClC,4BAA4B,EAC5B,oCAAoC,EACpC,QAAQ,EACR,wBAAwB,GACzB,8BAA6B;AAC9B,OAAO,EAAE,eAAe,EAAE,8BAA6B;AAEvD,OAAO,EACL,8BAA8B,EAC9B,0BAA0B,EAC1B,gCAAgC,EAChC,mBAAmB,EACnB,mBAAmB,GACpB,kCAAiC;AAClC,YAAY,EACV,0BAA0B,EAC1B,aAAa,GACd,kCAAiC"}
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","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,EACX,kBAAkB;
|
|
1
|
+
{"version":3,"file":"index.mjs","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,EACX,kBAAkB;AAanB,OAAO,EAAE,eAAe,EAAE,8BAA6B;AAEvD,OAAO,EACL,8BAA8B,EAC9B,0BAA0B,EAC1B,gCAAgC,EAChC,mBAAmB,EACnB,mBAAmB,EACpB,kCAAiC","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.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.
|
|
3
|
+
exports.processQueryResponse = void 0;
|
|
4
4
|
const superstruct_1 = require("@metamask/superstruct");
|
|
5
5
|
/**
|
|
6
6
|
* Process query responses, validating them using Superstruct if a struct is defined.
|
|
@@ -22,35 +22,4 @@ function processQueryResponse(queryKey, response, struct) {
|
|
|
22
22
|
return result;
|
|
23
23
|
}
|
|
24
24
|
exports.processQueryResponse = processQueryResponse;
|
|
25
|
-
/**
|
|
26
|
-
* Process mutation responses, validating them using Superstruct if a struct is defined.
|
|
27
|
-
*
|
|
28
|
-
* @param mutationKey - The mutation key.
|
|
29
|
-
* @param response - The mutation response
|
|
30
|
-
* @param struct - The struct defining the schema for the mutation response.
|
|
31
|
-
* @returns The mutation response, coerced by Superstruct if needed.
|
|
32
|
-
* @throws If the mutation response does not match the struct.
|
|
33
|
-
* @template InputResponse - The type of the response data being validated, e.g. `Json`.
|
|
34
|
-
* @template ResponseStruct - The struct used to validate and decode the response,
|
|
35
|
-
* e.g. `Struct<FetchOrdersResponse>`, or `undefined` when no validation is needed.
|
|
36
|
-
*/
|
|
37
|
-
function processMutationResponse(mutationKey, response, struct) {
|
|
38
|
-
if (!struct) {
|
|
39
|
-
// Type assertion: TypeScript cannot "see" that when `struct` is
|
|
40
|
-
// `undefined`, `response` satisfies the `InputResponse` branch of
|
|
41
|
-
// `Response` (even though we stated this fact in the conditional type
|
|
42
|
-
// above). This is because at this point in time, `ResponseStruct` — being a
|
|
43
|
-
// generic — is unresolved, which makes `Response` unresolved too. This is a
|
|
44
|
-
// limitation of the way that generics work. Therefore, we need to help
|
|
45
|
-
// TypeScript out.
|
|
46
|
-
return response;
|
|
47
|
-
}
|
|
48
|
-
const [error, result] = (0, superstruct_1.validate)(response, struct);
|
|
49
|
-
if (error) {
|
|
50
|
-
throw new Error(`Mutation function for "${mutationKey[0]}" returned an unexpected response: ${error.message}.`);
|
|
51
|
-
}
|
|
52
|
-
// Type assertion: See above.
|
|
53
|
-
return result;
|
|
54
|
-
}
|
|
55
|
-
exports.processMutationResponse = processMutationResponse;
|
|
56
25
|
//# sourceMappingURL=utils.cjs.map
|
package/dist/utils.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.cjs","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;;AAAA,uDAAyD;AAIzD;;;;;;;;GAQG;AACH,SAAgB,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,IAAA,sBAAQ,EAAC,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;AAlBD,oDAkBC
|
|
1
|
+
{"version":3,"file":"utils.cjs","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;;AAAA,uDAAyD;AAIzD;;;;;;;;GAQG;AACH,SAAgB,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,IAAA,sBAAQ,EAAC,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;AAlBD,oDAkBC","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"]}
|
package/dist/utils.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Struct } from "@metamask/superstruct";
|
|
2
|
-
import type {
|
|
2
|
+
import type { QueryKey } from "./BaseDataService.cjs";
|
|
3
3
|
/**
|
|
4
4
|
* Process query responses, validating them using Superstruct if a struct is defined.
|
|
5
5
|
*
|
|
@@ -10,17 +10,4 @@ import type { MutationKey, QueryKey } from "./BaseDataService.cjs";
|
|
|
10
10
|
* @throws If the query response does not match the struct.
|
|
11
11
|
*/
|
|
12
12
|
export declare function processQueryResponse<Response>(queryKey: QueryKey, response: Response, struct?: Struct<Response>): Response;
|
|
13
|
-
/**
|
|
14
|
-
* Process mutation responses, validating them using Superstruct if a struct is defined.
|
|
15
|
-
*
|
|
16
|
-
* @param mutationKey - The mutation key.
|
|
17
|
-
* @param response - The mutation response
|
|
18
|
-
* @param struct - The struct defining the schema for the mutation response.
|
|
19
|
-
* @returns The mutation response, coerced by Superstruct if needed.
|
|
20
|
-
* @throws If the mutation response does not match the struct.
|
|
21
|
-
* @template InputResponse - The type of the response data being validated, e.g. `Json`.
|
|
22
|
-
* @template ResponseStruct - The struct used to validate and decode the response,
|
|
23
|
-
* e.g. `Struct<FetchOrdersResponse>`, or `undefined` when no validation is needed.
|
|
24
|
-
*/
|
|
25
|
-
export declare function processMutationResponse<InputResponse, ResponseStruct extends Struct<any> | undefined = undefined>(mutationKey: MutationKey, response: InputResponse, struct?: ResponseStruct): ResponseStruct extends Struct<infer StructType> ? StructType : InputResponse;
|
|
26
13
|
//# sourceMappingURL=utils.d.cts.map
|
package/dist/utils.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.cts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAY,8BAA8B;AAEzD,OAAO,KAAK,EAAE,
|
|
1
|
+
{"version":3,"file":"utils.d.cts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAY,8BAA8B;AAEzD,OAAO,KAAK,EAAE,QAAQ,EAAE,8BAA6B;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.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Struct } from "@metamask/superstruct";
|
|
2
|
-
import type {
|
|
2
|
+
import type { QueryKey } from "./BaseDataService.mjs";
|
|
3
3
|
/**
|
|
4
4
|
* Process query responses, validating them using Superstruct if a struct is defined.
|
|
5
5
|
*
|
|
@@ -10,17 +10,4 @@ import type { MutationKey, QueryKey } from "./BaseDataService.mjs";
|
|
|
10
10
|
* @throws If the query response does not match the struct.
|
|
11
11
|
*/
|
|
12
12
|
export declare function processQueryResponse<Response>(queryKey: QueryKey, response: Response, struct?: Struct<Response>): Response;
|
|
13
|
-
/**
|
|
14
|
-
* Process mutation responses, validating them using Superstruct if a struct is defined.
|
|
15
|
-
*
|
|
16
|
-
* @param mutationKey - The mutation key.
|
|
17
|
-
* @param response - The mutation response
|
|
18
|
-
* @param struct - The struct defining the schema for the mutation response.
|
|
19
|
-
* @returns The mutation response, coerced by Superstruct if needed.
|
|
20
|
-
* @throws If the mutation response does not match the struct.
|
|
21
|
-
* @template InputResponse - The type of the response data being validated, e.g. `Json`.
|
|
22
|
-
* @template ResponseStruct - The struct used to validate and decode the response,
|
|
23
|
-
* e.g. `Struct<FetchOrdersResponse>`, or `undefined` when no validation is needed.
|
|
24
|
-
*/
|
|
25
|
-
export declare function processMutationResponse<InputResponse, ResponseStruct extends Struct<any> | undefined = undefined>(mutationKey: MutationKey, response: InputResponse, struct?: ResponseStruct): ResponseStruct extends Struct<infer StructType> ? StructType : InputResponse;
|
|
26
13
|
//# sourceMappingURL=utils.d.mts.map
|
package/dist/utils.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.mts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAY,8BAA8B;AAEzD,OAAO,KAAK,EAAE,
|
|
1
|
+
{"version":3,"file":"utils.d.mts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAY,8BAA8B;AAEzD,OAAO,KAAK,EAAE,QAAQ,EAAE,8BAA6B;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.mjs
CHANGED
|
@@ -18,34 +18,4 @@ export function processQueryResponse(queryKey, response, struct) {
|
|
|
18
18
|
}
|
|
19
19
|
return result;
|
|
20
20
|
}
|
|
21
|
-
/**
|
|
22
|
-
* Process mutation responses, validating them using Superstruct if a struct is defined.
|
|
23
|
-
*
|
|
24
|
-
* @param mutationKey - The mutation key.
|
|
25
|
-
* @param response - The mutation response
|
|
26
|
-
* @param struct - The struct defining the schema for the mutation response.
|
|
27
|
-
* @returns The mutation response, coerced by Superstruct if needed.
|
|
28
|
-
* @throws If the mutation response does not match the struct.
|
|
29
|
-
* @template InputResponse - The type of the response data being validated, e.g. `Json`.
|
|
30
|
-
* @template ResponseStruct - The struct used to validate and decode the response,
|
|
31
|
-
* e.g. `Struct<FetchOrdersResponse>`, or `undefined` when no validation is needed.
|
|
32
|
-
*/
|
|
33
|
-
export function processMutationResponse(mutationKey, response, struct) {
|
|
34
|
-
if (!struct) {
|
|
35
|
-
// Type assertion: TypeScript cannot "see" that when `struct` is
|
|
36
|
-
// `undefined`, `response` satisfies the `InputResponse` branch of
|
|
37
|
-
// `Response` (even though we stated this fact in the conditional type
|
|
38
|
-
// above). This is because at this point in time, `ResponseStruct` — being a
|
|
39
|
-
// generic — is unresolved, which makes `Response` unresolved too. This is a
|
|
40
|
-
// limitation of the way that generics work. Therefore, we need to help
|
|
41
|
-
// TypeScript out.
|
|
42
|
-
return response;
|
|
43
|
-
}
|
|
44
|
-
const [error, result] = validate(response, struct);
|
|
45
|
-
if (error) {
|
|
46
|
-
throw new Error(`Mutation function for "${mutationKey[0]}" returned an unexpected response: ${error.message}.`);
|
|
47
|
-
}
|
|
48
|
-
// Type assertion: See above.
|
|
49
|
-
return result;
|
|
50
|
-
}
|
|
51
21
|
//# sourceMappingURL=utils.mjs.map
|
package/dist/utils.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.mjs","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,8BAA8B;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
|
|
1
|
+
{"version":3,"file":"utils.mjs","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,8BAA8B;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"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask-previews/base-data-service",
|
|
3
|
-
"version": "1.0.0-preview-
|
|
3
|
+
"version": "1.0.0-preview-ec24abb79",
|
|
4
4
|
"description": "Provides utilities for building data services",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"Ethereum",
|
|
@@ -59,7 +59,7 @@
|
|
|
59
59
|
"@metamask/messenger": "^2.0.0",
|
|
60
60
|
"@metamask/storage-service": "^1.0.2",
|
|
61
61
|
"@metamask/superstruct": "^3.4.1",
|
|
62
|
-
"@metamask/utils": "^11.
|
|
62
|
+
"@metamask/utils": "^11.11.0",
|
|
63
63
|
"@tanstack/query-core": "^5.62.16",
|
|
64
64
|
"cockatiel": "^3.1.2",
|
|
65
65
|
"fast-deep-equal": "^3.1.3",
|
package/dist/loggers.cjs
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.createModuleLogger = exports.projectLogger = void 0;
|
|
4
|
-
const utils_1 = require("@metamask/utils");
|
|
5
|
-
Object.defineProperty(exports, "createModuleLogger", { enumerable: true, get: function () { return utils_1.createModuleLogger; } });
|
|
6
|
-
exports.projectLogger = (0, utils_1.createProjectLogger)('base-data-service');
|
|
7
|
-
//# sourceMappingURL=loggers.cjs.map
|
package/dist/loggers.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"loggers.cjs","sourceRoot":"","sources":["../src/loggers.ts"],"names":[],"mappings":";;;AAAA,2CAA0E;AAIjE,mGAJqB,0BAAkB,OAIrB;AAFd,QAAA,aAAa,GAAG,IAAA,2BAAmB,EAAC,mBAAmB,CAAC,CAAC","sourcesContent":["import { createProjectLogger, createModuleLogger } from '@metamask/utils';\n\nexport const projectLogger = createProjectLogger('base-data-service');\n\nexport { createModuleLogger };\n"]}
|
package/dist/loggers.d.cts
DELETED
package/dist/loggers.d.cts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"loggers.d.cts","sourceRoot":"","sources":["../src/loggers.ts"],"names":[],"mappings":";AAAA,OAAO,EAAuB,kBAAkB,EAAE,wBAAwB;AAE1E,eAAO,MAAM,aAAa,0BAA2C,CAAC;AAEtE,OAAO,EAAE,kBAAkB,EAAE,CAAC"}
|
package/dist/loggers.d.mts
DELETED
package/dist/loggers.d.mts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"loggers.d.mts","sourceRoot":"","sources":["../src/loggers.ts"],"names":[],"mappings":";AAAA,OAAO,EAAuB,kBAAkB,EAAE,wBAAwB;AAE1E,eAAO,MAAM,aAAa,0BAA2C,CAAC;AAEtE,OAAO,EAAE,kBAAkB,EAAE,CAAC"}
|
package/dist/loggers.mjs
DELETED
package/dist/loggers.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"loggers.mjs","sourceRoot":"","sources":["../src/loggers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,wBAAwB;AAE1E,MAAM,CAAC,MAAM,aAAa,GAAG,mBAAmB,CAAC,mBAAmB,CAAC,CAAC;AAEtE,OAAO,EAAE,kBAAkB,EAAE,CAAC","sourcesContent":["import { createProjectLogger, createModuleLogger } from '@metamask/utils';\n\nexport const projectLogger = createProjectLogger('base-data-service');\n\nexport { createModuleLogger };\n"]}
|