@metamask-previews/base-data-service 1.0.0-preview-abca9bcea → 1.0.0-preview-8bfa290fb
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 +8 -0
- package/dist/BaseDataService.cjs +86 -11
- package/dist/BaseDataService.cjs.map +1 -1
- package/dist/BaseDataService.d.cts +35 -4
- package/dist/BaseDataService.d.cts.map +1 -1
- package/dist/BaseDataService.d.mts +35 -4
- package/dist/BaseDataService.d.mts.map +1 -1
- package/dist/BaseDataService.mjs +88 -13
- 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/loggers.cjs +7 -0
- package/dist/loggers.cjs.map +1 -0
- package/dist/loggers.d.cts +5 -0
- package/dist/loggers.d.cts.map +1 -0
- package/dist/loggers.d.mts +5 -0
- package/dist/loggers.d.mts.map +1 -0
- package/dist/loggers.mjs +4 -0
- package/dist/loggers.mjs.map +1 -0
- package/dist/utils.cjs +32 -1
- package/dist/utils.cjs.map +1 -1
- package/dist/utils.d.cts +14 -1
- package/dist/utils.d.cts.map +1 -1
- package/dist/utils.d.mts +14 -1
- package/dist/utils.d.mts.map +1 -1
- package/dist/utils.mjs +30 -0
- package/dist/utils.mjs.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,14 @@ 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
|
+
|
|
10
18
|
### Changed
|
|
11
19
|
|
|
12
20
|
- Bump `@metamask/utils` from `^11.11.0` to `^11.12.0` ([#10076](https://github.com/MetaMask/core/pull/10076))
|
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, _BaseDataService_debouncedPersist, _BaseDataService_persistenceConfig, _BaseDataService_publishCacheUpdate, _BaseDataService_persistCache, _BaseDataService_loadCache;
|
|
16
|
+
var _BaseDataService_instances, _BaseDataService_messenger, _BaseDataService_externalMessenger, _BaseDataService_policy, _BaseDataService_queryClient, _BaseDataService_queryCacheUnsubscribe, _BaseDataService_mutationCacheUnsubscribe, _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,13 +23,20 @@ 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");
|
|
26
27
|
const utils_js_1 = require("./utils.cjs");
|
|
27
|
-
|
|
28
|
+
const log = (0, loggers_js_1.createModuleLogger)(loggers_js_1.projectLogger, 'BaseDataService');
|
|
29
|
+
/*
|
|
30
|
+
* Defaults to apply to all data service queries if no default option specified.
|
|
31
|
+
*/
|
|
28
32
|
const QUERY_CLIENT_DEFAULTS = {
|
|
29
33
|
queries: {
|
|
30
34
|
retry: false,
|
|
31
35
|
staleTime: (0, utils_1.inMilliseconds)(1, utils_1.Duration.Minute),
|
|
32
36
|
},
|
|
37
|
+
mutations: {
|
|
38
|
+
retry: false,
|
|
39
|
+
},
|
|
33
40
|
};
|
|
34
41
|
exports.STORAGE_SERVICE_KEY = 'cache';
|
|
35
42
|
class BaseDataService {
|
|
@@ -40,6 +47,7 @@ class BaseDataService {
|
|
|
40
47
|
_BaseDataService_policy.set(this, void 0);
|
|
41
48
|
_BaseDataService_queryClient.set(this, void 0);
|
|
42
49
|
_BaseDataService_queryCacheUnsubscribe.set(this, void 0);
|
|
50
|
+
_BaseDataService_mutationCacheUnsubscribe.set(this, void 0);
|
|
43
51
|
_BaseDataService_debouncedPersist.set(this, void 0);
|
|
44
52
|
_BaseDataService_persistenceConfig.set(this, void 0);
|
|
45
53
|
this.name = name;
|
|
@@ -57,7 +65,10 @@ class BaseDataService {
|
|
|
57
65
|
...QUERY_CLIENT_DEFAULTS.queries,
|
|
58
66
|
...queryClientConfig.defaultOptions?.queries,
|
|
59
67
|
},
|
|
60
|
-
mutations:
|
|
68
|
+
mutations: {
|
|
69
|
+
...QUERY_CLIENT_DEFAULTS.mutations,
|
|
70
|
+
...queryClientConfig.defaultOptions?.mutations,
|
|
71
|
+
},
|
|
61
72
|
},
|
|
62
73
|
}), "f");
|
|
63
74
|
__classPrivateFieldSet(this, _BaseDataService_persistenceConfig, persistenceConfig, "f");
|
|
@@ -75,8 +86,21 @@ class BaseDataService {
|
|
|
75
86
|
__classPrivateFieldSet(this, _BaseDataService_queryCacheUnsubscribe, __classPrivateFieldGet(this, _BaseDataService_queryClient, "f")
|
|
76
87
|
.getQueryCache()
|
|
77
88
|
.subscribe((event) => {
|
|
89
|
+
log('Query cache event emitted', event);
|
|
78
90
|
if (['added', 'updated', 'removed'].includes(event.type)) {
|
|
79
|
-
__classPrivateFieldGet(this, _BaseDataService_instances, "m", _BaseDataService_publishCacheUpdate).call(this, event.
|
|
91
|
+
__classPrivateFieldGet(this, _BaseDataService_instances, "m", _BaseDataService_publishCacheUpdate).call(this, 'query', event.type, event.query.queryHash);
|
|
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);
|
|
80
104
|
__classPrivateFieldGet(this, _BaseDataService_debouncedPersist, "f")?.call(this);
|
|
81
105
|
}
|
|
82
106
|
}), "f");
|
|
@@ -87,14 +111,15 @@ class BaseDataService {
|
|
|
87
111
|
*
|
|
88
112
|
* @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.
|
|
89
113
|
* Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
|
|
114
|
+
* @param options.queryFn - The query function.
|
|
90
115
|
* @param options.responseStruct - An optional struct for validating the response of the query function.
|
|
91
116
|
* @returns The query results.
|
|
92
117
|
*/
|
|
93
|
-
async fetchQuery({ responseStruct, ...options }) {
|
|
118
|
+
async fetchQuery({ queryFn, responseStruct, ...options }) {
|
|
94
119
|
return __classPrivateFieldGet(this, _BaseDataService_queryClient, "f").fetchQuery({
|
|
95
120
|
...options,
|
|
96
121
|
queryFn: async (context) => {
|
|
97
|
-
const response = await __classPrivateFieldGet(this, _BaseDataService_policy, "f").execute(() =>
|
|
122
|
+
const response = await __classPrivateFieldGet(this, _BaseDataService_policy, "f").execute(() => queryFn(context));
|
|
98
123
|
return (0, utils_js_1.processQueryResponse)(options.queryKey, response, responseStruct);
|
|
99
124
|
},
|
|
100
125
|
});
|
|
@@ -134,6 +159,43 @@ class BaseDataService {
|
|
|
134
159
|
const pageIndex = result.pageParams.findIndex((param) => (0, fast_deep_equal_1.default)(param, pageParam));
|
|
135
160
|
return result.pages[pageIndex];
|
|
136
161
|
}
|
|
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
|
+
}
|
|
137
199
|
/**
|
|
138
200
|
* Invalidate queries serviced by this data service.
|
|
139
201
|
*
|
|
@@ -159,25 +221,38 @@ class BaseDataService {
|
|
|
159
221
|
destroy() {
|
|
160
222
|
__classPrivateFieldGet(this, _BaseDataService_debouncedPersist, "f")?.cancel();
|
|
161
223
|
__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
|
+
}
|
|
162
232
|
__classPrivateFieldGet(this, _BaseDataService_queryClient, "f").clear();
|
|
163
233
|
this.messenger.clearSubscriptions();
|
|
164
234
|
this.messenger.clearActions();
|
|
165
235
|
}
|
|
166
236
|
}
|
|
167
237
|
exports.BaseDataService = BaseDataService;
|
|
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(
|
|
169
|
-
const state =
|
|
238
|
+
_BaseDataService_messenger = new WeakMap(), _BaseDataService_externalMessenger = new WeakMap(), _BaseDataService_policy = new WeakMap(), _BaseDataService_queryClient = new WeakMap(), _BaseDataService_queryCacheUnsubscribe = new WeakMap(), _BaseDataService_mutationCacheUnsubscribe = new WeakMap(), _BaseDataService_debouncedPersist = new WeakMap(), _BaseDataService_persistenceConfig = new WeakMap(), _BaseDataService_instances = new WeakSet(), _BaseDataService_publishCacheUpdate = function _BaseDataService_publishCacheUpdate(objectType, eventType, hash) {
|
|
239
|
+
const state = eventType === 'added' || eventType === 'updated'
|
|
170
240
|
? (0, query_core_1.dehydrate)(__classPrivateFieldGet(this, _BaseDataService_queryClient, "f"), {
|
|
171
|
-
shouldDehydrateQuery: (query) => query.queryHash === hash,
|
|
241
|
+
shouldDehydrateQuery: (query) => objectType === 'query' && query.queryHash === hash,
|
|
242
|
+
shouldDehydrateMutation: (mutation) => objectType === 'mutation' &&
|
|
243
|
+
mutation.options.mutationKey !== undefined &&
|
|
244
|
+
(0, query_core_1.hashKey)(mutation.options.mutationKey) === hash,
|
|
172
245
|
})
|
|
173
246
|
: null;
|
|
174
247
|
__classPrivateFieldGet(this, _BaseDataService_messenger, "f").publish(`${this.name}:cacheUpdated`, {
|
|
175
|
-
type,
|
|
248
|
+
type: eventType,
|
|
249
|
+
objectType,
|
|
176
250
|
hash,
|
|
177
251
|
state,
|
|
178
252
|
});
|
|
179
253
|
__classPrivateFieldGet(this, _BaseDataService_messenger, "f").publish(`${this.name}:cacheUpdated:${hash}`, {
|
|
180
|
-
type,
|
|
254
|
+
type: eventType,
|
|
255
|
+
objectType,
|
|
181
256
|
state,
|
|
182
257
|
});
|
|
183
258
|
}, _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,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,oDAA8C;QAE9C,qDAA8C;QAqBrD,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QAEjB,2EAA2E;QAC3E,kFAAkF;QAClF,yDAAyD;QACzD,6FAA6F;QAC7F,uBAAA,IA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AK,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[]] | readonly [string, ...Json[]];\n\n/**\n * The supertype of all messengers, scoped to a namespace.\n *\n * @template Namespace - The namespace for the messenger's own actions and\n * events.\n */\nexport type BaseMessenger<Namespace extends string> = Messenger<\n Namespace,\n ActionConstraint,\n EventConstraint,\n // Use `any` to allow any parent to be set. `any` is harmless in a type constraint anyway,\n // it's the one totally safe place to use it.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any\n>;\n\nexport type DataServiceGranularCacheUpdatedPayload =\n | { type: 'added' | 'updated'; state: DehydratedState }\n | {\n type: 'removed';\n state: null;\n };\n\nexport type DataServiceCacheUpdatedPayload =\n DataServiceGranularCacheUpdatedPayload & {\n hash: string;\n };\n\ntype CacheUpdatedType = DataServiceCacheUpdatedPayload['type'];\n\nexport type DataServiceInvalidateQueriesAction<ServiceName extends string> = {\n type: `${ServiceName}:invalidateQueries`;\n handler: BaseDataService<\n ServiceName,\n BaseMessenger<ServiceName>\n >['invalidateQueries'];\n};\n\nexport type DataServiceActions<ServiceName extends string> =\n DataServiceInvalidateQueriesAction<ServiceName>;\n\ntype DataServiceAllowedActions =\n | StorageServiceGetItemAction\n | StorageServiceSetItemAction\n | StorageServiceRemoveItemAction;\n\nexport type DataServiceCacheUpdatedEvent<ServiceName extends string> = {\n type: `${ServiceName}:cacheUpdated`;\n payload: [DataServiceCacheUpdatedPayload];\n};\n\nexport type DataServiceGranularCacheUpdatedEvent<ServiceName extends string> = {\n type: `${ServiceName}:cacheUpdated:${string}`;\n payload: [DataServiceGranularCacheUpdatedPayload];\n};\n\nexport type DataServiceEvents<ServiceName extends string> =\n | DataServiceCacheUpdatedEvent<ServiceName>\n | DataServiceGranularCacheUpdatedEvent<ServiceName>;\n\n// Defaults to apply to all data service queries if no default option specified\nconst QUERY_CLIENT_DEFAULTS: DefaultOptions = {\n queries: {\n retry: false,\n staleTime: inMilliseconds(1, Duration.Minute),\n },\n};\n\nexport const STORAGE_SERVICE_KEY = 'cache';\n\n/**\n * Options for persistence configuration.\n */\nexport type PersistenceConfiguration = {\n /**\n * The maximum age before the cache is treated as expired in milliseconds.\n * This is relevant for rehydrating the state during initialization,\n * if the cached state is too old it will be discarded.\n */\n maxAge: number;\n /**\n * The number of milliseconds to wait before triggering persistence following a cache update.\n */\n writeDelay?: number;\n /**\n * The maximum number of milliseconds to wait between persistence writes.\n */\n maxWriteDelay?: number;\n};\n\ntype PersistedCache = {\n state: DehydratedState;\n timestamp: number;\n};\n\nexport class BaseDataService<\n ServiceName extends string,\n ServiceMessenger extends BaseMessenger<ServiceName>,\n> {\n public readonly name: ServiceName;\n\n readonly #messenger: Messenger<\n ServiceName,\n DataServiceActions<ServiceName>,\n DataServiceEvents<ServiceName>\n >;\n\n readonly #externalMessenger: Messenger<\n ServiceName,\n DataServiceAllowedActions\n >;\n\n protected messenger: ServiceMessenger;\n\n readonly #policy: ServicePolicy;\n\n readonly #queryClient: QueryClient;\n\n readonly #queryCacheUnsubscribe: () => void;\n\n readonly #debouncedPersist?: DebouncedFunc<() => void>;\n\n readonly #persistenceConfig?: PersistenceConfiguration;\n\n constructor({\n name,\n messenger,\n queryClientConfig = {},\n policyOptions,\n persistenceConfig,\n }: {\n name: ServiceName;\n messenger: DataServiceActions<ServiceName>['type'] extends\n | MessengerActions<ServiceMessenger>['type']\n | DataServiceAllowedActions['type']\n ? DataServiceEvents<ServiceName>['type'] extends MessengerEvents<ServiceMessenger>['type']\n ? ServiceMessenger\n : never\n : never;\n queryClientConfig?: QueryClientConfig;\n policyOptions?: CreateServicePolicyOptions;\n persistenceConfig?: PersistenceConfiguration;\n }) {\n this.name = name;\n\n // We store two narrowly-typed messengers alongside the generic public one:\n // - #messenger handles the service's own action registration and event publishing\n // - #externalMessenger handles calls to external actions\n // Splitting them avoids TypeScript issues with mixing template-literals with regular strings\n this.#messenger = messenger as unknown as Messenger<\n ServiceName,\n DataServiceActions<ServiceName>,\n DataServiceEvents<ServiceName>\n >;\n this.#externalMessenger = messenger as unknown as Messenger<\n ServiceName,\n DataServiceAllowedActions\n >;\n this.messenger = messenger;\n\n this.#queryClient = new QueryClient({\n ...queryClientConfig,\n defaultOptions: {\n queries: {\n ...QUERY_CLIENT_DEFAULTS.queries,\n ...queryClientConfig.defaultOptions?.queries,\n },\n mutations: queryClientConfig.defaultOptions?.mutations,\n },\n });\n\n this.#persistenceConfig = persistenceConfig;\n\n this.#policy = createServicePolicy(policyOptions);\n\n this.#debouncedPersist =\n this.#persistenceConfig &&\n debounce(\n () => {\n this.#persistCache().catch(\n /* istanbul ignore next */\n (error) => this.#messenger.captureException?.(error),\n );\n },\n this.#persistenceConfig.writeDelay ??\n inMilliseconds(10, Duration.Second),\n {\n maxWait:\n this.#persistenceConfig.maxWriteDelay ??\n inMilliseconds(1, Duration.Minute),\n },\n );\n\n this.#queryCacheUnsubscribe = this.#queryClient\n .getQueryCache()\n .subscribe((event) => {\n if (['added', 'updated', 'removed'].includes(event.type)) {\n this.#publishCacheUpdate(\n event.query.queryHash,\n event.type as CacheUpdatedType,\n );\n\n this.#debouncedPersist?.();\n }\n });\n\n this.#messenger.registerActionHandler(\n `${this.name}:invalidateQueries`,\n this.invalidateQueries.bind(this),\n );\n }\n\n /**\n * Fetch a query.\n *\n * @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.\n * Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.\n * @param options.responseStruct - An optional struct for validating the response of the query function.\n * @returns The query results.\n */\n protected async fetchQuery<\n TQueryFnData extends Json,\n TError = DefaultError,\n TDataStruct extends Struct<TQueryFnData> | undefined = undefined,\n TData = TDataStruct extends Struct<infer StructType>\n ? StructType\n : TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n >({\n responseStruct,\n ...options\n }: WithRequired<\n OmitKeyof<\n FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'retry' | 'retryDelay' | 'queryFn'\n >,\n 'queryKey'\n > & {\n queryFn: QueryFunction<TQueryFnData, TQueryKey>;\n responseStruct?: TDataStruct;\n }): Promise<TData> {\n return this.#queryClient.fetchQuery({\n ...options,\n queryFn: async (context) => {\n const response = await this.#policy.execute(() =>\n options.queryFn(context),\n );\n return processQueryResponse(options.queryKey, response, responseStruct);\n },\n });\n }\n\n /**\n * Fetch a paginated query.\n *\n * @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.\n * Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.\n * @param options.responseStruct - An optional struct for validating the response of the query function.\n * @param pageParam - An optional page parameter.\n * @returns The query result, exclusively the requested page is returned.\n */\n protected async fetchInfiniteQuery<\n TQueryFnData extends Json,\n TError = DefaultError,\n TDataStruct extends Struct<TQueryFnData> | undefined = undefined,\n TData extends TQueryFnData = TDataStruct extends Struct<infer StructType>\n ? StructType\n : TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam extends Json = Json,\n >(\n {\n responseStruct,\n ...options\n }: WithRequired<\n OmitKeyof<\n FetchQueryOptions<\n TQueryFnData,\n TError,\n InfiniteData<TData, TPageParam>,\n TQueryKey,\n TPageParam\n >,\n 'retry' | 'retryDelay' | 'queryFn' | 'initialPageParam'\n >,\n 'queryKey'\n > &\n InfiniteQueryPageParamsOptions<TQueryFnData, TPageParam> & {\n queryFn: QueryFunction<TQueryFnData, TQueryKey, TPageParam>;\n responseStruct?: TDataStruct;\n },\n pageParam?: TPageParam,\n ): Promise<TData> {\n const cache = this.#queryClient.getQueryCache();\n\n const query = cache.find<\n TQueryFnData,\n TError,\n InfiniteData<TData, TPageParam>\n >({\n queryKey: options.queryKey,\n });\n\n if (!query?.state.data || !pageParam) {\n const result = await this.#queryClient.fetchInfiniteQuery({\n ...options,\n initialPageParam: pageParam ?? options.initialPageParam,\n queryFn: async (context) => {\n const response = await this.#policy.execute(async () =>\n options.queryFn({\n ...context,\n pageParam: context.meta?.pageParam ?? context.pageParam,\n }),\n );\n return processQueryResponse(\n options.queryKey,\n response,\n responseStruct,\n );\n },\n });\n\n return result.pages[0];\n }\n\n const { pages, pageParams } = query.state.data;\n const next = options.getNextPageParam(\n pages[pages.length - 1],\n pages,\n pageParams[pageParams.length - 1],\n pageParams,\n );\n\n const direction = deepEqual(pageParam, next) ? 'forward' : 'backward';\n\n const result = await query.fetch(\n { ...query.options, meta: { pageParam } },\n { meta: { fetchMore: { direction } } },\n );\n\n const pageIndex = result.pageParams.findIndex((param) =>\n deepEqual(param, pageParam),\n );\n\n return result.pages[pageIndex];\n }\n\n /**\n * Invalidate queries serviced by this data service.\n *\n * @param filters - Optional filter for selecting specific queries.\n * @param options - Additional optional options for query invalidations.\n * @returns Nothing.\n */\n async invalidateQueries(\n filters?: InvalidateQueryFilters<QueryKey>,\n options?: InvalidateOptions,\n ): Promise<void> {\n return this.#queryClient.invalidateQueries(filters, options);\n }\n\n /**\n * Initialize the service, rehydrating the cache with persisted data if possible.\n */\n init(): void {\n this.#loadCache().catch(\n /* istanbul ignore next */\n (error) => this.#messenger.captureException?.(error),\n );\n }\n\n /**\n * Prepares the service for garbage collection. This should be extended\n * by any subclasses to clean up any additional connections or events.\n */\n destroy(): void {\n this.#debouncedPersist?.cancel();\n this.#queryCacheUnsubscribe();\n this.#queryClient.clear();\n this.messenger.clearSubscriptions();\n this.messenger.clearActions();\n }\n\n /**\n * Publish `cacheUpdated` events when a given query changes.\n *\n * @param hash The hash of the query.\n * @param type The type of cache update.\n */\n #publishCacheUpdate(hash: string, type: CacheUpdatedType): void {\n const state =\n type === 'added' || type === 'updated'\n ? dehydrate(this.#queryClient, {\n shouldDehydrateQuery: (query) => query.queryHash === hash,\n })\n : null;\n\n this.#messenger.publish(\n `${this.name}:cacheUpdated` as const,\n {\n type,\n hash,\n state,\n } as DataServiceCacheUpdatedPayload,\n );\n\n this.#messenger.publish(\n `${this.name}:cacheUpdated:${hash}` as const,\n {\n type,\n state,\n } as DataServiceGranularCacheUpdatedPayload,\n );\n }\n\n /**\n * Persist the query client cache using the StorageService, if the cache is not empty.\n *\n * @returns Nothing.\n */\n async #persistCache(): Promise<void> {\n const state = dehydrate(this.#queryClient, {\n // This is the default, but we specify it to be explicit.\n shouldDehydrateQuery: (query) => query.state.status === 'success',\n });\n\n if (state.queries.length === 0 && state.mutations.length === 0) {\n await this.#externalMessenger.call(\n 'StorageService:removeItem',\n this.name,\n STORAGE_SERVICE_KEY,\n );\n return;\n }\n\n const cache: PersistedCache = {\n timestamp: Date.now(),\n state,\n };\n\n await this.#externalMessenger.call(\n 'StorageService:setItem',\n this.name,\n STORAGE_SERVICE_KEY,\n cache as unknown as Json,\n );\n }\n\n /**\n * Load the query client cache from the StorageService, if persistence is configured\n * and the persisted cache is not expired.\n *\n * @returns Nothing.\n */\n async #loadCache(): Promise<void> {\n if (!this.#persistenceConfig) {\n return;\n }\n\n const { result: untypedCache } = await this.#externalMessenger.call(\n 'StorageService:getItem',\n this.name,\n STORAGE_SERVICE_KEY,\n );\n\n if (!untypedCache) {\n return;\n }\n\n const cache = untypedCache as unknown as PersistedCache;\n\n if (Date.now() - cache.timestamp >= this.#persistenceConfig.maxAge) {\n await this.#externalMessenger.call(\n 'StorageService:removeItem',\n this.name,\n STORAGE_SERVICE_KEY,\n );\n return;\n }\n\n hydrate(this.#queryClient, cache.state);\n }\n}\n"]}
|
|
1
|
+
{"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,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ClB,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 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"]}
|
|
@@ -2,9 +2,15 @@ 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, OmitKeyof, QueryClientConfig, QueryFunction, WithRequired } from "@tanstack/query-core";
|
|
5
|
+
import { DefaultError, DehydratedState, FetchQueryOptions, InfiniteData, InfiniteQueryPageParamsOptions, InvalidateOptions, InvalidateQueryFilters, MutationOptions, OmitKeyof, QueryClientConfig, QueryFunction, WithRequired, MutationFunction } from "@tanstack/query-core";
|
|
6
6
|
import { CreateServicePolicyOptions } from "./createServicePolicy.cjs";
|
|
7
|
-
|
|
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;
|
|
8
14
|
/**
|
|
9
15
|
* The supertype of all messengers, scoped to a namespace.
|
|
10
16
|
*
|
|
@@ -13,12 +19,14 @@ export type QueryKey = [string, ...Json[]] | readonly [string, ...Json[]];
|
|
|
13
19
|
*/
|
|
14
20
|
export type BaseMessenger<Namespace extends string> = Messenger<Namespace, ActionConstraint, EventConstraint, any>;
|
|
15
21
|
export type DataServiceGranularCacheUpdatedPayload = {
|
|
22
|
+
objectType: 'query' | 'mutation';
|
|
23
|
+
} & ({
|
|
16
24
|
type: 'added' | 'updated';
|
|
17
25
|
state: DehydratedState;
|
|
18
26
|
} | {
|
|
19
27
|
type: 'removed';
|
|
20
28
|
state: null;
|
|
21
|
-
};
|
|
29
|
+
});
|
|
22
30
|
export type DataServiceCacheUpdatedPayload = DataServiceGranularCacheUpdatedPayload & {
|
|
23
31
|
hash: string;
|
|
24
32
|
};
|
|
@@ -73,10 +81,11 @@ export declare class BaseDataService<ServiceName extends string, ServiceMessenge
|
|
|
73
81
|
*
|
|
74
82
|
* @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.
|
|
75
83
|
* Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
|
|
84
|
+
* @param options.queryFn - The query function.
|
|
76
85
|
* @param options.responseStruct - An optional struct for validating the response of the query function.
|
|
77
86
|
* @returns The query results.
|
|
78
87
|
*/
|
|
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'> & {
|
|
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>({ queryFn, responseStruct, ...options }: WithRequired<OmitKeyof<FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>, 'retry' | 'retryDelay' | 'queryFn'>, 'queryKey'> & {
|
|
80
89
|
queryFn: QueryFunction<TQueryFnData, TQueryKey>;
|
|
81
90
|
responseStruct?: TDataStruct;
|
|
82
91
|
}): Promise<TData>;
|
|
@@ -93,6 +102,28 @@ export declare class BaseDataService<ServiceName extends string, ServiceMessenge
|
|
|
93
102
|
queryFn: QueryFunction<TQueryFnData, TQueryKey, TPageParam>;
|
|
94
103
|
responseStruct?: TDataStruct;
|
|
95
104
|
}, 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>;
|
|
96
127
|
/**
|
|
97
128
|
* Invalidate queries serviced by this data service.
|
|
98
129
|
*
|
|
@@ -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,SAAS,EAET,iBAAiB,EACjB,aAAa,EACb,YAAY,
|
|
1
|
+
{"version":3,"file":"BaseDataService.d.cts","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"mappings":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AU,EAAE,gBAAgB,CAAC,eAAe,EAAE,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC;QACpE,cAAc,CAAC,EAAE,WAAW,CAAC;QAC7B,QAAQ,CAAC,EAAE,MAAM,CAAC;KACnB,GAAG,OAAO,CAAC,KAAK,CAAC;IAiClB;;;;;;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;CA8HhB"}
|
|
@@ -2,9 +2,15 @@ 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, OmitKeyof, QueryClientConfig, QueryFunction, WithRequired } from "@tanstack/query-core";
|
|
5
|
+
import { DefaultError, DehydratedState, FetchQueryOptions, InfiniteData, InfiniteQueryPageParamsOptions, InvalidateOptions, InvalidateQueryFilters, MutationOptions, OmitKeyof, QueryClientConfig, QueryFunction, WithRequired, MutationFunction } from "@tanstack/query-core";
|
|
6
6
|
import { CreateServicePolicyOptions } from "./createServicePolicy.mjs";
|
|
7
|
-
|
|
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;
|
|
8
14
|
/**
|
|
9
15
|
* The supertype of all messengers, scoped to a namespace.
|
|
10
16
|
*
|
|
@@ -13,12 +19,14 @@ export type QueryKey = [string, ...Json[]] | readonly [string, ...Json[]];
|
|
|
13
19
|
*/
|
|
14
20
|
export type BaseMessenger<Namespace extends string> = Messenger<Namespace, ActionConstraint, EventConstraint, any>;
|
|
15
21
|
export type DataServiceGranularCacheUpdatedPayload = {
|
|
22
|
+
objectType: 'query' | 'mutation';
|
|
23
|
+
} & ({
|
|
16
24
|
type: 'added' | 'updated';
|
|
17
25
|
state: DehydratedState;
|
|
18
26
|
} | {
|
|
19
27
|
type: 'removed';
|
|
20
28
|
state: null;
|
|
21
|
-
};
|
|
29
|
+
});
|
|
22
30
|
export type DataServiceCacheUpdatedPayload = DataServiceGranularCacheUpdatedPayload & {
|
|
23
31
|
hash: string;
|
|
24
32
|
};
|
|
@@ -73,10 +81,11 @@ export declare class BaseDataService<ServiceName extends string, ServiceMessenge
|
|
|
73
81
|
*
|
|
74
82
|
* @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.
|
|
75
83
|
* Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
|
|
84
|
+
* @param options.queryFn - The query function.
|
|
76
85
|
* @param options.responseStruct - An optional struct for validating the response of the query function.
|
|
77
86
|
* @returns The query results.
|
|
78
87
|
*/
|
|
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'> & {
|
|
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>({ queryFn, responseStruct, ...options }: WithRequired<OmitKeyof<FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>, 'retry' | 'retryDelay' | 'queryFn'>, 'queryKey'> & {
|
|
80
89
|
queryFn: QueryFunction<TQueryFnData, TQueryKey>;
|
|
81
90
|
responseStruct?: TDataStruct;
|
|
82
91
|
}): Promise<TData>;
|
|
@@ -93,6 +102,28 @@ export declare class BaseDataService<ServiceName extends string, ServiceMessenge
|
|
|
93
102
|
queryFn: QueryFunction<TQueryFnData, TQueryKey, TPageParam>;
|
|
94
103
|
responseStruct?: TDataStruct;
|
|
95
104
|
}, 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>;
|
|
96
127
|
/**
|
|
97
128
|
* Invalidate queries serviced by this data service.
|
|
98
129
|
*
|
|
@@ -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,SAAS,EAET,iBAAiB,EACjB,aAAa,EACb,YAAY,
|
|
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,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;OAEG;IACH,IAAI,IAAI,IAAI;IAOZ;;;OAGG;IACH,OAAO,IAAI,IAAI;CA8HhB"}
|
package/dist/BaseDataService.mjs
CHANGED
|
@@ -9,7 +9,7 @@ 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, _BaseDataService_debouncedPersist, _BaseDataService_persistenceConfig, _BaseDataService_publishCacheUpdate, _BaseDataService_persistCache, _BaseDataService_loadCache;
|
|
12
|
+
var _BaseDataService_instances, _BaseDataService_messenger, _BaseDataService_externalMessenger, _BaseDataService_policy, _BaseDataService_queryClient, _BaseDataService_queryCacheUnsubscribe, _BaseDataService_mutationCacheUnsubscribe, _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,19 +19,26 @@ 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 } from "@tanstack/query-core";
|
|
22
|
+
import { QueryClient, dehydrate, hydrate, hashKey } 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
|
-
|
|
28
|
+
import { createModuleLogger, projectLogger } from "./loggers.mjs";
|
|
29
|
+
import { processMutationResponse, processQueryResponse } from "./utils.mjs";
|
|
30
|
+
const log = createModuleLogger(projectLogger, 'BaseDataService');
|
|
31
|
+
/*
|
|
32
|
+
* Defaults to apply to all data service queries if no default option specified.
|
|
33
|
+
*/
|
|
30
34
|
const QUERY_CLIENT_DEFAULTS = {
|
|
31
35
|
queries: {
|
|
32
36
|
retry: false,
|
|
33
37
|
staleTime: inMilliseconds(1, Duration.Minute),
|
|
34
38
|
},
|
|
39
|
+
mutations: {
|
|
40
|
+
retry: false,
|
|
41
|
+
},
|
|
35
42
|
};
|
|
36
43
|
export const STORAGE_SERVICE_KEY = 'cache';
|
|
37
44
|
export class BaseDataService {
|
|
@@ -42,6 +49,7 @@ export class BaseDataService {
|
|
|
42
49
|
_BaseDataService_policy.set(this, void 0);
|
|
43
50
|
_BaseDataService_queryClient.set(this, void 0);
|
|
44
51
|
_BaseDataService_queryCacheUnsubscribe.set(this, void 0);
|
|
52
|
+
_BaseDataService_mutationCacheUnsubscribe.set(this, void 0);
|
|
45
53
|
_BaseDataService_debouncedPersist.set(this, void 0);
|
|
46
54
|
_BaseDataService_persistenceConfig.set(this, void 0);
|
|
47
55
|
this.name = name;
|
|
@@ -59,7 +67,10 @@ export class BaseDataService {
|
|
|
59
67
|
...QUERY_CLIENT_DEFAULTS.queries,
|
|
60
68
|
...queryClientConfig.defaultOptions?.queries,
|
|
61
69
|
},
|
|
62
|
-
mutations:
|
|
70
|
+
mutations: {
|
|
71
|
+
...QUERY_CLIENT_DEFAULTS.mutations,
|
|
72
|
+
...queryClientConfig.defaultOptions?.mutations,
|
|
73
|
+
},
|
|
63
74
|
},
|
|
64
75
|
}), "f");
|
|
65
76
|
__classPrivateFieldSet(this, _BaseDataService_persistenceConfig, persistenceConfig, "f");
|
|
@@ -77,8 +88,21 @@ export class BaseDataService {
|
|
|
77
88
|
__classPrivateFieldSet(this, _BaseDataService_queryCacheUnsubscribe, __classPrivateFieldGet(this, _BaseDataService_queryClient, "f")
|
|
78
89
|
.getQueryCache()
|
|
79
90
|
.subscribe((event) => {
|
|
91
|
+
log('Query cache event emitted', event);
|
|
80
92
|
if (['added', 'updated', 'removed'].includes(event.type)) {
|
|
81
|
-
__classPrivateFieldGet(this, _BaseDataService_instances, "m", _BaseDataService_publishCacheUpdate).call(this, event.
|
|
93
|
+
__classPrivateFieldGet(this, _BaseDataService_instances, "m", _BaseDataService_publishCacheUpdate).call(this, 'query', event.type, event.query.queryHash);
|
|
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);
|
|
82
106
|
__classPrivateFieldGet(this, _BaseDataService_debouncedPersist, "f")?.call(this);
|
|
83
107
|
}
|
|
84
108
|
}), "f");
|
|
@@ -89,14 +113,15 @@ export class BaseDataService {
|
|
|
89
113
|
*
|
|
90
114
|
* @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.
|
|
91
115
|
* Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
|
|
116
|
+
* @param options.queryFn - The query function.
|
|
92
117
|
* @param options.responseStruct - An optional struct for validating the response of the query function.
|
|
93
118
|
* @returns The query results.
|
|
94
119
|
*/
|
|
95
|
-
async fetchQuery({ responseStruct, ...options }) {
|
|
120
|
+
async fetchQuery({ queryFn, responseStruct, ...options }) {
|
|
96
121
|
return __classPrivateFieldGet(this, _BaseDataService_queryClient, "f").fetchQuery({
|
|
97
122
|
...options,
|
|
98
123
|
queryFn: async (context) => {
|
|
99
|
-
const response = await __classPrivateFieldGet(this, _BaseDataService_policy, "f").execute(() =>
|
|
124
|
+
const response = await __classPrivateFieldGet(this, _BaseDataService_policy, "f").execute(() => queryFn(context));
|
|
100
125
|
return processQueryResponse(options.queryKey, response, responseStruct);
|
|
101
126
|
},
|
|
102
127
|
});
|
|
@@ -136,6 +161,43 @@ export class BaseDataService {
|
|
|
136
161
|
const pageIndex = result.pageParams.findIndex((param) => deepEqual(param, pageParam));
|
|
137
162
|
return result.pages[pageIndex];
|
|
138
163
|
}
|
|
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
|
+
}
|
|
139
201
|
/**
|
|
140
202
|
* Invalidate queries serviced by this data service.
|
|
141
203
|
*
|
|
@@ -161,24 +223,37 @@ export class BaseDataService {
|
|
|
161
223
|
destroy() {
|
|
162
224
|
__classPrivateFieldGet(this, _BaseDataService_debouncedPersist, "f")?.cancel();
|
|
163
225
|
__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
|
+
}
|
|
164
234
|
__classPrivateFieldGet(this, _BaseDataService_queryClient, "f").clear();
|
|
165
235
|
this.messenger.clearSubscriptions();
|
|
166
236
|
this.messenger.clearActions();
|
|
167
237
|
}
|
|
168
238
|
}
|
|
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(
|
|
170
|
-
const state =
|
|
239
|
+
_BaseDataService_messenger = new WeakMap(), _BaseDataService_externalMessenger = new WeakMap(), _BaseDataService_policy = new WeakMap(), _BaseDataService_queryClient = new WeakMap(), _BaseDataService_queryCacheUnsubscribe = new WeakMap(), _BaseDataService_mutationCacheUnsubscribe = new WeakMap(), _BaseDataService_debouncedPersist = new WeakMap(), _BaseDataService_persistenceConfig = new WeakMap(), _BaseDataService_instances = new WeakSet(), _BaseDataService_publishCacheUpdate = function _BaseDataService_publishCacheUpdate(objectType, eventType, hash) {
|
|
240
|
+
const state = eventType === 'added' || eventType === 'updated'
|
|
171
241
|
? dehydrate(__classPrivateFieldGet(this, _BaseDataService_queryClient, "f"), {
|
|
172
|
-
shouldDehydrateQuery: (query) => query.queryHash === hash,
|
|
242
|
+
shouldDehydrateQuery: (query) => objectType === 'query' && query.queryHash === hash,
|
|
243
|
+
shouldDehydrateMutation: (mutation) => objectType === 'mutation' &&
|
|
244
|
+
mutation.options.mutationKey !== undefined &&
|
|
245
|
+
hashKey(mutation.options.mutationKey) === hash,
|
|
173
246
|
})
|
|
174
247
|
: null;
|
|
175
248
|
__classPrivateFieldGet(this, _BaseDataService_messenger, "f").publish(`${this.name}:cacheUpdated`, {
|
|
176
|
-
type,
|
|
249
|
+
type: eventType,
|
|
250
|
+
objectType,
|
|
177
251
|
hash,
|
|
178
252
|
state,
|
|
179
253
|
});
|
|
180
254
|
__classPrivateFieldGet(this, _BaseDataService_messenger, "f").publish(`${this.name}:cacheUpdated:${hash}`, {
|
|
181
|
-
type,
|
|
255
|
+
type: eventType,
|
|
256
|
+
objectType,
|
|
182
257
|
state,
|
|
183
258
|
});
|
|
184
259
|
}, _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,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;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AAC,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 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[]] | readonly [string, ...Json[]];\n\n/**\n * The supertype of all messengers, scoped to a namespace.\n *\n * @template Namespace - The namespace for the messenger's own actions and\n * events.\n */\nexport type BaseMessenger<Namespace extends string> = Messenger<\n Namespace,\n ActionConstraint,\n EventConstraint,\n // Use `any` to allow any parent to be set. `any` is harmless in a type constraint anyway,\n // it's the one totally safe place to use it.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any\n>;\n\nexport type DataServiceGranularCacheUpdatedPayload =\n | { type: 'added' | 'updated'; state: DehydratedState }\n | {\n type: 'removed';\n state: null;\n };\n\nexport type DataServiceCacheUpdatedPayload =\n DataServiceGranularCacheUpdatedPayload & {\n hash: string;\n };\n\ntype CacheUpdatedType = DataServiceCacheUpdatedPayload['type'];\n\nexport type DataServiceInvalidateQueriesAction<ServiceName extends string> = {\n type: `${ServiceName}:invalidateQueries`;\n handler: BaseDataService<\n ServiceName,\n BaseMessenger<ServiceName>\n >['invalidateQueries'];\n};\n\nexport type DataServiceActions<ServiceName extends string> =\n DataServiceInvalidateQueriesAction<ServiceName>;\n\ntype DataServiceAllowedActions =\n | StorageServiceGetItemAction\n | StorageServiceSetItemAction\n | StorageServiceRemoveItemAction;\n\nexport type DataServiceCacheUpdatedEvent<ServiceName extends string> = {\n type: `${ServiceName}:cacheUpdated`;\n payload: [DataServiceCacheUpdatedPayload];\n};\n\nexport type DataServiceGranularCacheUpdatedEvent<ServiceName extends string> = {\n type: `${ServiceName}:cacheUpdated:${string}`;\n payload: [DataServiceGranularCacheUpdatedPayload];\n};\n\nexport type DataServiceEvents<ServiceName extends string> =\n | DataServiceCacheUpdatedEvent<ServiceName>\n | DataServiceGranularCacheUpdatedEvent<ServiceName>;\n\n// Defaults to apply to all data service queries if no default option specified\nconst QUERY_CLIENT_DEFAULTS: DefaultOptions = {\n queries: {\n retry: false,\n staleTime: inMilliseconds(1, Duration.Minute),\n },\n};\n\nexport const STORAGE_SERVICE_KEY = 'cache';\n\n/**\n * Options for persistence configuration.\n */\nexport type PersistenceConfiguration = {\n /**\n * The maximum age before the cache is treated as expired in milliseconds.\n * This is relevant for rehydrating the state during initialization,\n * if the cached state is too old it will be discarded.\n */\n maxAge: number;\n /**\n * The number of milliseconds to wait before triggering persistence following a cache update.\n */\n writeDelay?: number;\n /**\n * The maximum number of milliseconds to wait between persistence writes.\n */\n maxWriteDelay?: number;\n};\n\ntype PersistedCache = {\n state: DehydratedState;\n timestamp: number;\n};\n\nexport class BaseDataService<\n ServiceName extends string,\n ServiceMessenger extends BaseMessenger<ServiceName>,\n> {\n public readonly name: ServiceName;\n\n readonly #messenger: Messenger<\n ServiceName,\n DataServiceActions<ServiceName>,\n DataServiceEvents<ServiceName>\n >;\n\n readonly #externalMessenger: Messenger<\n ServiceName,\n DataServiceAllowedActions\n >;\n\n protected messenger: ServiceMessenger;\n\n readonly #policy: ServicePolicy;\n\n readonly #queryClient: QueryClient;\n\n readonly #queryCacheUnsubscribe: () => void;\n\n readonly #debouncedPersist?: DebouncedFunc<() => void>;\n\n readonly #persistenceConfig?: PersistenceConfiguration;\n\n constructor({\n name,\n messenger,\n queryClientConfig = {},\n policyOptions,\n persistenceConfig,\n }: {\n name: ServiceName;\n messenger: DataServiceActions<ServiceName>['type'] extends\n | MessengerActions<ServiceMessenger>['type']\n | DataServiceAllowedActions['type']\n ? DataServiceEvents<ServiceName>['type'] extends MessengerEvents<ServiceMessenger>['type']\n ? ServiceMessenger\n : never\n : never;\n queryClientConfig?: QueryClientConfig;\n policyOptions?: CreateServicePolicyOptions;\n persistenceConfig?: PersistenceConfiguration;\n }) {\n this.name = name;\n\n // We store two narrowly-typed messengers alongside the generic public one:\n // - #messenger handles the service's own action registration and event publishing\n // - #externalMessenger handles calls to external actions\n // Splitting them avoids TypeScript issues with mixing template-literals with regular strings\n this.#messenger = messenger as unknown as Messenger<\n ServiceName,\n DataServiceActions<ServiceName>,\n DataServiceEvents<ServiceName>\n >;\n this.#externalMessenger = messenger as unknown as Messenger<\n ServiceName,\n DataServiceAllowedActions\n >;\n this.messenger = messenger;\n\n this.#queryClient = new QueryClient({\n ...queryClientConfig,\n defaultOptions: {\n queries: {\n ...QUERY_CLIENT_DEFAULTS.queries,\n ...queryClientConfig.defaultOptions?.queries,\n },\n mutations: queryClientConfig.defaultOptions?.mutations,\n },\n });\n\n this.#persistenceConfig = persistenceConfig;\n\n this.#policy = createServicePolicy(policyOptions);\n\n this.#debouncedPersist =\n this.#persistenceConfig &&\n debounce(\n () => {\n this.#persistCache().catch(\n /* istanbul ignore next */\n (error) => this.#messenger.captureException?.(error),\n );\n },\n this.#persistenceConfig.writeDelay ??\n inMilliseconds(10, Duration.Second),\n {\n maxWait:\n this.#persistenceConfig.maxWriteDelay ??\n inMilliseconds(1, Duration.Minute),\n },\n );\n\n this.#queryCacheUnsubscribe = this.#queryClient\n .getQueryCache()\n .subscribe((event) => {\n if (['added', 'updated', 'removed'].includes(event.type)) {\n this.#publishCacheUpdate(\n event.query.queryHash,\n event.type as CacheUpdatedType,\n );\n\n this.#debouncedPersist?.();\n }\n });\n\n this.#messenger.registerActionHandler(\n `${this.name}:invalidateQueries`,\n this.invalidateQueries.bind(this),\n );\n }\n\n /**\n * Fetch a query.\n *\n * @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.\n * Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.\n * @param options.responseStruct - An optional struct for validating the response of the query function.\n * @returns The query results.\n */\n protected async fetchQuery<\n TQueryFnData extends Json,\n TError = DefaultError,\n TDataStruct extends Struct<TQueryFnData> | undefined = undefined,\n TData = TDataStruct extends Struct<infer StructType>\n ? StructType\n : TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n >({\n responseStruct,\n ...options\n }: WithRequired<\n OmitKeyof<\n FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'retry' | 'retryDelay' | 'queryFn'\n >,\n 'queryKey'\n > & {\n queryFn: QueryFunction<TQueryFnData, TQueryKey>;\n responseStruct?: TDataStruct;\n }): Promise<TData> {\n return this.#queryClient.fetchQuery({\n ...options,\n queryFn: async (context) => {\n const response = await this.#policy.execute(() =>\n options.queryFn(context),\n );\n return processQueryResponse(options.queryKey, response, responseStruct);\n },\n });\n }\n\n /**\n * Fetch a paginated query.\n *\n * @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.\n * Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.\n * @param options.responseStruct - An optional struct for validating the response of the query function.\n * @param pageParam - An optional page parameter.\n * @returns The query result, exclusively the requested page is returned.\n */\n protected async fetchInfiniteQuery<\n TQueryFnData extends Json,\n TError = DefaultError,\n TDataStruct extends Struct<TQueryFnData> | undefined = undefined,\n TData extends TQueryFnData = TDataStruct extends Struct<infer StructType>\n ? StructType\n : TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam extends Json = Json,\n >(\n {\n responseStruct,\n ...options\n }: WithRequired<\n OmitKeyof<\n FetchQueryOptions<\n TQueryFnData,\n TError,\n InfiniteData<TData, TPageParam>,\n TQueryKey,\n TPageParam\n >,\n 'retry' | 'retryDelay' | 'queryFn' | 'initialPageParam'\n >,\n 'queryKey'\n > &\n InfiniteQueryPageParamsOptions<TQueryFnData, TPageParam> & {\n queryFn: QueryFunction<TQueryFnData, TQueryKey, TPageParam>;\n responseStruct?: TDataStruct;\n },\n pageParam?: TPageParam,\n ): Promise<TData> {\n const cache = this.#queryClient.getQueryCache();\n\n const query = cache.find<\n TQueryFnData,\n TError,\n InfiniteData<TData, TPageParam>\n >({\n queryKey: options.queryKey,\n });\n\n if (!query?.state.data || !pageParam) {\n const result = await this.#queryClient.fetchInfiniteQuery({\n ...options,\n initialPageParam: pageParam ?? options.initialPageParam,\n queryFn: async (context) => {\n const response = await this.#policy.execute(async () =>\n options.queryFn({\n ...context,\n pageParam: context.meta?.pageParam ?? context.pageParam,\n }),\n );\n return processQueryResponse(\n options.queryKey,\n response,\n responseStruct,\n );\n },\n });\n\n return result.pages[0];\n }\n\n const { pages, pageParams } = query.state.data;\n const next = options.getNextPageParam(\n pages[pages.length - 1],\n pages,\n pageParams[pageParams.length - 1],\n pageParams,\n );\n\n const direction = deepEqual(pageParam, next) ? 'forward' : 'backward';\n\n const result = await query.fetch(\n { ...query.options, meta: { pageParam } },\n { meta: { fetchMore: { direction } } },\n );\n\n const pageIndex = result.pageParams.findIndex((param) =>\n deepEqual(param, pageParam),\n );\n\n return result.pages[pageIndex];\n }\n\n /**\n * Invalidate queries serviced by this data service.\n *\n * @param filters - Optional filter for selecting specific queries.\n * @param options - Additional optional options for query invalidations.\n * @returns Nothing.\n */\n async invalidateQueries(\n filters?: InvalidateQueryFilters<QueryKey>,\n options?: InvalidateOptions,\n ): Promise<void> {\n return this.#queryClient.invalidateQueries(filters, options);\n }\n\n /**\n * Initialize the service, rehydrating the cache with persisted data if possible.\n */\n init(): void {\n this.#loadCache().catch(\n /* istanbul ignore next */\n (error) => this.#messenger.captureException?.(error),\n );\n }\n\n /**\n * Prepares the service for garbage collection. This should be extended\n * by any subclasses to clean up any additional connections or events.\n */\n destroy(): void {\n this.#debouncedPersist?.cancel();\n this.#queryCacheUnsubscribe();\n this.#queryClient.clear();\n this.messenger.clearSubscriptions();\n this.messenger.clearActions();\n }\n\n /**\n * Publish `cacheUpdated` events when a given query changes.\n *\n * @param hash The hash of the query.\n * @param type The type of cache update.\n */\n #publishCacheUpdate(hash: string, type: CacheUpdatedType): void {\n const state =\n type === 'added' || type === 'updated'\n ? dehydrate(this.#queryClient, {\n shouldDehydrateQuery: (query) => query.queryHash === hash,\n })\n : null;\n\n this.#messenger.publish(\n `${this.name}:cacheUpdated` as const,\n {\n type,\n hash,\n state,\n } as DataServiceCacheUpdatedPayload,\n );\n\n this.#messenger.publish(\n `${this.name}:cacheUpdated:${hash}` as const,\n {\n type,\n state,\n } as DataServiceGranularCacheUpdatedPayload,\n );\n }\n\n /**\n * Persist the query client cache using the StorageService, if the cache is not empty.\n *\n * @returns Nothing.\n */\n async #persistCache(): Promise<void> {\n const state = dehydrate(this.#queryClient, {\n // This is the default, but we specify it to be explicit.\n shouldDehydrateQuery: (query) => query.state.status === 'success',\n });\n\n if (state.queries.length === 0 && state.mutations.length === 0) {\n await this.#externalMessenger.call(\n 'StorageService:removeItem',\n this.name,\n STORAGE_SERVICE_KEY,\n );\n return;\n }\n\n const cache: PersistedCache = {\n timestamp: Date.now(),\n state,\n };\n\n await this.#externalMessenger.call(\n 'StorageService:setItem',\n this.name,\n STORAGE_SERVICE_KEY,\n cache as unknown as Json,\n );\n }\n\n /**\n * Load the query client cache from the StorageService, if persistence is configured\n * and the persisted cache is not expired.\n *\n * @returns Nothing.\n */\n async #loadCache(): Promise<void> {\n if (!this.#persistenceConfig) {\n return;\n }\n\n const { result: untypedCache } = await this.#externalMessenger.call(\n 'StorageService:getItem',\n this.name,\n STORAGE_SERVICE_KEY,\n );\n\n if (!untypedCache) {\n return;\n }\n\n const cache = untypedCache as unknown as PersistedCache;\n\n if (Date.now() - cache.timestamp >= this.#persistenceConfig.maxAge) {\n await this.#externalMessenger.call(\n 'StorageService:removeItem',\n this.name,\n STORAGE_SERVICE_KEY,\n );\n return;\n }\n\n hydrate(this.#queryClient, cache.state);\n }\n}\n"]}
|
|
1
|
+
{"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,EAWL,WAAW,EAIX,SAAS,EACT,OAAO,EACP,OAAO,EAER,6BAA6B;AAC9B,OAAO,UAAS,wBAAwB;;;;AAGxC,OAAO,EACL,mBAAmB,EAGpB,kCAAiC;AAClC,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,sBAAqB;AACjE,OAAO,EAAE,uBAAuB,EAAE,oBAAoB,EAAE,oBAAmB;AAE3E,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,iBAAiB,CAAC,CAAC;AAmFjE;;GAEG;AACH,MAAM,qBAAqB,GAAmB;IAC5C,OAAO,EAAE;QACP,KAAK,EAAE,KAAK;QACZ,SAAS,EAAE,cAAc,CAAC,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC;KAC9C;IACD,SA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wB,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"]}
|
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;AAeZ,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 MutationKey,\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, PersistenceConfiguration, } from "./BaseDataService.cjs";
|
|
3
|
+
export type { DataServiceActions, DataServiceEvents, DataServiceCacheUpdatedPayload, DataServiceGranularCacheUpdatedPayload, DataServiceInvalidateQueriesAction, DataServiceCacheUpdatedEvent, DataServiceGranularCacheUpdatedEvent, QueryKey, MutationKey, 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,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"}
|
|
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,WAAW,EACX,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, PersistenceConfiguration, } from "./BaseDataService.mjs";
|
|
3
|
+
export type { DataServiceActions, DataServiceEvents, DataServiceCacheUpdatedPayload, DataServiceGranularCacheUpdatedPayload, DataServiceInvalidateQueriesAction, DataServiceCacheUpdatedEvent, DataServiceGranularCacheUpdatedEvent, QueryKey, MutationKey, 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,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"}
|
|
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,WAAW,EACX,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;AAcnB,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 MutationKey,\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/loggers.cjs
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
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
|
|
@@ -0,0 +1 @@
|
|
|
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"]}
|
|
@@ -0,0 +1 @@
|
|
|
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"}
|
|
@@ -0,0 +1 @@
|
|
|
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
ADDED
|
@@ -0,0 +1 @@
|
|
|
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"]}
|
package/dist/utils.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.processQueryResponse = void 0;
|
|
3
|
+
exports.processMutationResponse = 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,4 +22,35 @@ 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;
|
|
25
56
|
//# 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","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"]}
|
|
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;AAED;;;;;;;;;;;GAWG;AACH,SAAgB,uBAAuB,CAUrC,WAAwB,EACxB,QAAuB,EACvB,MAAuB;IAavB,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,gEAAgE;QAChE,kEAAkE;QAClE,sEAAsE;QACtE,4EAA4E;QAC5E,4EAA4E;QAC5E,uEAAuE;QACvE,kBAAkB;QAClB,OAAO,QAA+B,CAAC;IACzC,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,0BAA0B,WAAW,CAAC,CAAC,CAAC,sCAAsC,KAAK,CAAC,OAAO,GAAG,CAC/F,CAAC;IACJ,CAAC;IAED,6BAA6B;IAC7B,OAAO,MAA6B,CAAC;AACvC,CAAC;AA9CD,0DA8CC","sourcesContent":["import { Struct, validate } from '@metamask/superstruct';\n\nimport type { MutationKey, 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\n/**\n * Process mutation responses, validating them using Superstruct if a struct is defined.\n *\n * @param mutationKey - The mutation key.\n * @param response - The mutation response\n * @param struct - The struct defining the schema for the mutation response.\n * @returns The mutation response, coerced by Superstruct if needed.\n * @throws If the mutation response does not match the struct.\n * @template InputResponse - The type of the response data being validated, e.g. `Json`.\n * @template ResponseStruct - The struct used to validate and decode the response,\n * e.g. `Struct<FetchOrdersResponse>`, or `undefined` when no validation is needed.\n */\nexport function processMutationResponse<\n InputResponse,\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 ResponseStruct extends Struct<any> | undefined = undefined,\n>(\n mutationKey: MutationKey,\n response: InputResponse,\n struct?: ResponseStruct,\n // We don't want this to be a type parameter as it should not be customizable\n // (it is only derived).\n): ResponseStruct extends Struct<infer StructType>\n ? StructType\n : InputResponse {\n // Because we aren't defining the return type as a type parameter,\n // we need to restate it so we can reuse it below.\n type Response =\n ResponseStruct extends Struct<infer StructType>\n ? StructType\n : InputResponse;\n\n if (!struct) {\n // Type assertion: TypeScript cannot \"see\" that when `struct` is\n // `undefined`, `response` satisfies the `InputResponse` branch of\n // `Response` (even though we stated this fact in the conditional type\n // above). This is because at this point in time, `ResponseStruct` — being a\n // generic — is unresolved, which makes `Response` unresolved too. This is a\n // limitation of the way that generics work. Therefore, we need to help\n // TypeScript out.\n return response as unknown as Response;\n }\n\n const [error, result] = validate(response, struct);\n\n if (error) {\n throw new Error(\n `Mutation function for \"${mutationKey[0]}\" returned an unexpected response: ${error.message}.`,\n );\n }\n\n // Type assertion: See above.\n return result as unknown as Response;\n}\n"]}
|
package/dist/utils.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Struct } from "@metamask/superstruct";
|
|
2
|
-
import type { QueryKey } from "./BaseDataService.cjs";
|
|
2
|
+
import type { MutationKey, QueryKey } from "./BaseDataService.cjs";
|
|
3
3
|
/**
|
|
4
4
|
* Process query responses, validating them using Superstruct if a struct is defined.
|
|
5
5
|
*
|
|
@@ -10,4 +10,17 @@ import type { 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;
|
|
13
26
|
//# 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,QAAQ,EAAE,8BAA6B;
|
|
1
|
+
{"version":3,"file":"utils.d.cts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAY,8BAA8B;AAEzD,OAAO,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,8BAA6B;AAElE;;;;;;;;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;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,uBAAuB,CACrC,aAAa,EAOb,cAAc,SAAS,MAAM,CAAC,GAAG,CAAC,GAAG,SAAS,GAAG,SAAS,EAE1D,WAAW,EAAE,WAAW,EACxB,QAAQ,EAAE,aAAa,EACvB,MAAM,CAAC,EAAE,cAAc,GAGtB,cAAc,SAAS,MAAM,CAAC,MAAM,UAAU,CAAC,GAC9C,UAAU,GACV,aAAa,CA6BhB"}
|
package/dist/utils.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Struct } from "@metamask/superstruct";
|
|
2
|
-
import type { QueryKey } from "./BaseDataService.mjs";
|
|
2
|
+
import type { MutationKey, QueryKey } from "./BaseDataService.mjs";
|
|
3
3
|
/**
|
|
4
4
|
* Process query responses, validating them using Superstruct if a struct is defined.
|
|
5
5
|
*
|
|
@@ -10,4 +10,17 @@ import type { 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;
|
|
13
26
|
//# 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,QAAQ,EAAE,8BAA6B;
|
|
1
|
+
{"version":3,"file":"utils.d.mts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAY,8BAA8B;AAEzD,OAAO,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,8BAA6B;AAElE;;;;;;;;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;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,uBAAuB,CACrC,aAAa,EAOb,cAAc,SAAS,MAAM,CAAC,GAAG,CAAC,GAAG,SAAS,GAAG,SAAS,EAE1D,WAAW,EAAE,WAAW,EACxB,QAAQ,EAAE,aAAa,EACvB,MAAM,CAAC,EAAE,cAAc,GAGtB,cAAc,SAAS,MAAM,CAAC,MAAM,UAAU,CAAC,GAC9C,UAAU,GACV,aAAa,CA6BhB"}
|
package/dist/utils.mjs
CHANGED
|
@@ -18,4 +18,34 @@ 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
|
+
}
|
|
21
51
|
//# 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","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"]}
|
|
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;AAED;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,uBAAuB,CAUrC,WAAwB,EACxB,QAAuB,EACvB,MAAuB;IAavB,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,gEAAgE;QAChE,kEAAkE;QAClE,sEAAsE;QACtE,4EAA4E;QAC5E,4EAA4E;QAC5E,uEAAuE;QACvE,kBAAkB;QAClB,OAAO,QAA+B,CAAC;IACzC,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,0BAA0B,WAAW,CAAC,CAAC,CAAC,sCAAsC,KAAK,CAAC,OAAO,GAAG,CAC/F,CAAC;IACJ,CAAC;IAED,6BAA6B;IAC7B,OAAO,MAA6B,CAAC;AACvC,CAAC","sourcesContent":["import { Struct, validate } from '@metamask/superstruct';\n\nimport type { MutationKey, 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\n/**\n * Process mutation responses, validating them using Superstruct if a struct is defined.\n *\n * @param mutationKey - The mutation key.\n * @param response - The mutation response\n * @param struct - The struct defining the schema for the mutation response.\n * @returns The mutation response, coerced by Superstruct if needed.\n * @throws If the mutation response does not match the struct.\n * @template InputResponse - The type of the response data being validated, e.g. `Json`.\n * @template ResponseStruct - The struct used to validate and decode the response,\n * e.g. `Struct<FetchOrdersResponse>`, or `undefined` when no validation is needed.\n */\nexport function processMutationResponse<\n InputResponse,\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 ResponseStruct extends Struct<any> | undefined = undefined,\n>(\n mutationKey: MutationKey,\n response: InputResponse,\n struct?: ResponseStruct,\n // We don't want this to be a type parameter as it should not be customizable\n // (it is only derived).\n): ResponseStruct extends Struct<infer StructType>\n ? StructType\n : InputResponse {\n // Because we aren't defining the return type as a type parameter,\n // we need to restate it so we can reuse it below.\n type Response =\n ResponseStruct extends Struct<infer StructType>\n ? StructType\n : InputResponse;\n\n if (!struct) {\n // Type assertion: TypeScript cannot \"see\" that when `struct` is\n // `undefined`, `response` satisfies the `InputResponse` branch of\n // `Response` (even though we stated this fact in the conditional type\n // above). This is because at this point in time, `ResponseStruct` — being a\n // generic — is unresolved, which makes `Response` unresolved too. This is a\n // limitation of the way that generics work. Therefore, we need to help\n // TypeScript out.\n return response as unknown as Response;\n }\n\n const [error, result] = validate(response, struct);\n\n if (error) {\n throw new Error(\n `Mutation function for \"${mutationKey[0]}\" returned an unexpected response: ${error.message}.`,\n );\n }\n\n // Type assertion: See above.\n return result as unknown as Response;\n}\n"]}
|