@metamask-previews/base-data-service 0.1.3-preview-6426280bb → 0.1.3-preview-c2ef75d18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +0 -3
- package/dist/BaseDataService.cjs +25 -55
- package/dist/BaseDataService.cjs.map +1 -1
- package/dist/BaseDataService.d.cts +11 -34
- package/dist/BaseDataService.d.cts.map +1 -1
- package/dist/BaseDataService.d.mts +11 -34
- package/dist/BaseDataService.d.mts.map +1 -1
- package/dist/BaseDataService.mjs +25 -55
- package/dist/BaseDataService.mjs.map +1 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -38,9 +38,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
38
38
|
|
|
39
39
|
- **BREAKING:** Remove `TPageData` type parameter from `invalidateQueries` method ([#9526](https://github.com/MetaMask/core/pull/9526))
|
|
40
40
|
- This is technically a breaking change, but this was not used in any of our codebases
|
|
41
|
-
- **BREAKING:** Bump `@tanstack/query-core` from `^4.43.0` to `^5.62.16` ([#9712](https://github.com/MetaMask/core/pull/9712))
|
|
42
|
-
- The option types accepted by `fetchQuery`, `fetchInfiniteQuery`, and `invalidateQueries` now follow the query-core v5 API. Subclasses need to rename `cacheTime` to `gcTime`.
|
|
43
|
-
- `fetchInfiniteQuery` now requires `initialPageParam` and `getNextPageParam`, matching query-core's options for infinite queries. This also lets `TPageParam` be inferred instead of spelled out in the type parameters.
|
|
44
41
|
- Bump `@metamask/utils` from `^11.9.0` to `^11.11.0` ([#9074](https://github.com/MetaMask/core/pull/9074))
|
|
45
42
|
- Bump `@metamask/controller-utils` from `^12.1.0` to `^12.3.0` ([#9058](https://github.com/MetaMask/core/pull/9058), [#9083](https://github.com/MetaMask/core/pull/9083), [#9218](https://github.com/MetaMask/core/pull/9218))
|
|
46
43
|
- Bump `@metamask/messenger` from `^1.2.0` to `^2.0.0` ([#9392](https://github.com/MetaMask/core/pull/9392))
|
package/dist/BaseDataService.cjs
CHANGED
|
@@ -83,13 +83,8 @@ class BaseDataService {
|
|
|
83
83
|
/**
|
|
84
84
|
* Fetch a query.
|
|
85
85
|
*
|
|
86
|
-
* @param options - The options defining the query.
|
|
87
|
-
*
|
|
88
|
-
* restrictions:
|
|
89
|
-
* - `queryKey` and `queryFn` are required
|
|
90
|
-
* - `queryFn` must be a function, not a skip token
|
|
91
|
-
* - `retry` and `retryDelay` are not available (retries can be customized
|
|
92
|
-
* using the constructor's `servicePolicyOptions`).
|
|
86
|
+
* @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.
|
|
87
|
+
* Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
|
|
93
88
|
* @returns The query results.
|
|
94
89
|
*/
|
|
95
90
|
async fetchQuery(options) {
|
|
@@ -101,64 +96,39 @@ class BaseDataService {
|
|
|
101
96
|
/**
|
|
102
97
|
* Fetch a paginated query.
|
|
103
98
|
*
|
|
104
|
-
* @param options - The options defining the query.
|
|
105
|
-
*
|
|
106
|
-
* few differences:
|
|
107
|
-
* - `queryKey` and `queryFn` are required
|
|
108
|
-
* - `queryFn` must be a function, not a skip token
|
|
109
|
-
* - `retry` and `retryDelay` are not available (retries can be customized
|
|
110
|
-
* using the constructor's `servicePolicyOptions`).
|
|
99
|
+
* @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.
|
|
100
|
+
* Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
|
|
111
101
|
* @param pageParam - An optional page parameter.
|
|
112
|
-
* @returns
|
|
113
|
-
* this is different from `@tanstack/query-core`'s `fetchInfiniteQuery`
|
|
114
|
-
* method, which returns all pages.
|
|
102
|
+
* @returns The query result, exclusively the requested page is returned.
|
|
115
103
|
*/
|
|
116
104
|
async fetchInfiniteQuery(options, pageParam) {
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
// only falls back when the per-call param itself is missing.
|
|
120
|
-
const requestedPageParam = pageParam ?? options.initialPageParam;
|
|
121
|
-
const query = __classPrivateFieldGet(this, _BaseDataService_queryClient, "f")
|
|
122
|
-
.getQueryCache()
|
|
123
|
-
.find({
|
|
105
|
+
const cache = __classPrivateFieldGet(this, _BaseDataService_queryClient, "f").getQueryCache();
|
|
106
|
+
const query = cache.find({
|
|
124
107
|
queryKey: options.queryKey,
|
|
125
108
|
});
|
|
126
|
-
|
|
127
|
-
// `fetchInfiniteQuery`, which reuses the cached page while the query is
|
|
128
|
-
// fresh. A cold jump starts the query at the requested page by using it as
|
|
129
|
-
// the initial page param.
|
|
130
|
-
if (!query?.state.data ||
|
|
131
|
-
(0, fast_deep_equal_1.default)(requestedPageParam, options.initialPageParam)) {
|
|
109
|
+
if (!query?.state.data || pageParam === undefined) {
|
|
132
110
|
const result = await __classPrivateFieldGet(this, _BaseDataService_queryClient, "f").fetchInfiniteQuery({
|
|
133
111
|
...options,
|
|
134
|
-
|
|
135
|
-
|
|
112
|
+
queryFn: (context) => __classPrivateFieldGet(this, _BaseDataService_policy, "f").execute(() => options.queryFn({
|
|
113
|
+
...context,
|
|
114
|
+
pageParam: context.pageParam ?? pageParam,
|
|
115
|
+
})),
|
|
136
116
|
});
|
|
137
117
|
return result.pages[0];
|
|
138
118
|
}
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
const
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
__classPrivateFieldGet(this, _BaseDataService_queryClient, "f").setQueryData(options.queryKey, (0, fast_deep_equal_1.default)(requestedPageParam, nextPageParam)
|
|
153
|
-
? {
|
|
154
|
-
pages: [...pages, page],
|
|
155
|
-
pageParams: [...pageParams, requestedPageParam],
|
|
156
|
-
}
|
|
157
|
-
: {
|
|
158
|
-
pages: [page, ...pages],
|
|
159
|
-
pageParams: [requestedPageParam, ...pageParams],
|
|
160
|
-
});
|
|
161
|
-
return page;
|
|
119
|
+
const { pages } = query.state.data;
|
|
120
|
+
const previous = options.getPreviousPageParam?.(pages[0], pages);
|
|
121
|
+
const direction = (0, fast_deep_equal_1.default)(pageParam, previous) ? 'backward' : 'forward';
|
|
122
|
+
const result = await query.fetch(undefined, {
|
|
123
|
+
meta: {
|
|
124
|
+
fetchMore: {
|
|
125
|
+
direction,
|
|
126
|
+
pageParam,
|
|
127
|
+
},
|
|
128
|
+
},
|
|
129
|
+
});
|
|
130
|
+
const pageIndex = result.pageParams.findIndex((param) => (0, fast_deep_equal_1.default)(param, pageParam));
|
|
131
|
+
return result.pages[pageIndex];
|
|
162
132
|
}
|
|
163
133
|
/**
|
|
164
134
|
* Invalidate queries serviced by this data service.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseDataService.cjs","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,mDAI6B;AAM7B,2CAA2D;AAE3D,qDAgB8B;AAC9B,sEAAwC;AACxC,mCAAiD;AAEjD,sEAIkC;AAiElC,+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,GAOlB;;QAnCQ,6CAIP;QAEO,qDAGP;QAIO,0CAAuB;QAEvB,+CAA0B;QAE1B,yDAAmC;QAEnC,oDAA8C;QAE9C,qDAA8C;QAerD,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QAEjB,2EAA2E;QAC3E,kFAAkF;QAClF,yDAAyD;QACzD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CAAC,YAAY,EAAE,CAAC;QAClB,OAAO;IACT,CAAC;IAED,MAAM,KAAK,GAAG,YAAyC,CAAC;IAExD,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,SAAS,IAAI,uBAAA,IAAI,0CAAmB,CAAC,MAAM,EAAE,CAAC;QACnE,MAAM,uBAAA,IAAI,0CAAmB,CAAC,IAAI,CAChC,2BAA2B,EAC3B,IAAI,CAAC,IAAI,EACT,2BAAmB,CACpB,CAAC;QACF,OAAO;IACT,CAAC;IAED,IAAA,oBAAO,EAAC,uBAAA,IAAI,oCAAa,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;AAC1C,CAAC","sourcesContent":["import {\n Messenger,\n ActionConstraint,\n EventConstraint,\n} from '@metamask/messenger';\nimport type {\n StorageServiceGetItemAction,\n StorageServiceRemoveItemAction,\n StorageServiceSetItemAction,\n} from '@metamask/storage-service';\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';\n\n// Data service queries use the following format: ['ServiceActionName', ...params]\nexport type QueryKey = [string, ...Json[]];\n\n/**\n * The supertype of all messengers, scoped to a namespace.\n *\n * @template Namespace - The namespace for the messenger's own actions and\n * events.\n */\nexport type BaseMessenger<Namespace extends string> = Messenger<\n Namespace,\n ActionConstraint,\n EventConstraint,\n // Use `any` to allow any parent to be set. `any` is harmless in a type constraint anyway,\n // it's the one totally safe place to use it.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any\n>;\n\nexport type DataServiceGranularCacheUpdatedPayload =\n | { type: 'added' | 'updated'; state: DehydratedState }\n | {\n type: 'removed';\n state: null;\n };\n\nexport type DataServiceCacheUpdatedPayload =\n DataServiceGranularCacheUpdatedPayload & {\n hash: string;\n };\n\ntype CacheUpdatedType = DataServiceCacheUpdatedPayload['type'];\n\nexport type DataServiceInvalidateQueriesAction<ServiceName extends string> = {\n type: `${ServiceName}:invalidateQueries`;\n handler: BaseDataService<\n ServiceName,\n BaseMessenger<ServiceName>\n >['invalidateQueries'];\n};\n\nexport type DataServiceActions<ServiceName extends string> =\n DataServiceInvalidateQueriesAction<ServiceName>;\n\ntype DataServiceAllowedActions =\n | StorageServiceGetItemAction\n | StorageServiceSetItemAction\n | StorageServiceRemoveItemAction;\n\nexport type DataServiceCacheUpdatedEvent<ServiceName extends string> = {\n type: `${ServiceName}:cacheUpdated`;\n payload: [DataServiceCacheUpdatedPayload];\n};\n\nexport type DataServiceGranularCacheUpdatedEvent<ServiceName extends string> = {\n type: `${ServiceName}:cacheUpdated:${string}`;\n payload: [DataServiceGranularCacheUpdatedPayload];\n};\n\nexport type DataServiceEvents<ServiceName extends string> =\n | DataServiceCacheUpdatedEvent<ServiceName>\n | DataServiceGranularCacheUpdatedEvent<ServiceName>;\n\n// Defaults to apply to all data service queries if no default option specified\nconst QUERY_CLIENT_DEFAULTS: DefaultOptions = {\n queries: {\n retry: false,\n staleTime: inMilliseconds(1, Duration.Minute),\n },\n};\n\nexport const STORAGE_SERVICE_KEY = 'cache';\n\n/**\n * Options for persistence configuration.\n */\nexport type PersistenceConfiguration = {\n /**\n * The maximum age before the cache is treated as expired in milliseconds.\n * This is relevant for rehydrating the state during initialization,\n * if the cached state is too old it will be discarded.\n */\n maxAge: number;\n /**\n * The number of milliseconds to wait before triggering persistence following a cache update.\n */\n writeDelay?: number;\n /**\n * The maximum number of milliseconds to wait between persistence writes.\n */\n maxWriteDelay?: number;\n};\n\ntype PersistedCache = {\n state: DehydratedState;\n timestamp: number;\n};\n\nexport class BaseDataService<\n ServiceName extends string,\n ServiceMessenger extends BaseMessenger<ServiceName>,\n> {\n public readonly name: ServiceName;\n\n readonly #messenger: Messenger<\n ServiceName,\n DataServiceActions<ServiceName>,\n DataServiceEvents<ServiceName>\n >;\n\n readonly #externalMessenger: Messenger<\n ServiceName,\n DataServiceAllowedActions\n >;\n\n protected messenger: ServiceMessenger;\n\n readonly #policy: ServicePolicy;\n\n readonly #queryClient: QueryClient;\n\n readonly #queryCacheUnsubscribe: () => void;\n\n readonly #debouncedPersist?: DebouncedFunc<() => void>;\n\n readonly #persistenceConfig?: PersistenceConfiguration;\n\n constructor({\n name,\n messenger,\n queryClientConfig = {},\n policyOptions,\n persistenceConfig,\n }: {\n name: ServiceName;\n messenger: ServiceMessenger;\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. Note that although this\n * method wraps `fetchQuery` from `@tanstack/query-core`, there are a few\n * restrictions:\n * - `queryKey` and `queryFn` are required\n * - `queryFn` must be a function, not a skip token\n * - `retry` and `retryDelay` are not available (retries can be customized\n * using the constructor's `servicePolicyOptions`).\n * @returns The query results.\n */\n protected async fetchQuery<\n TQueryFnData extends Json,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n >(\n options: WithRequired<\n OmitKeyof<\n FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'retry' | 'retryDelay' | 'queryFn'\n >,\n 'queryKey'\n > & {\n // @tanstack/query-core's fetchQuery function accepts a \"skip\" token, but\n // data services always provide a concrete query function.\n queryFn: QueryFunction<TQueryFnData, TQueryKey>;\n },\n ): Promise<TData> {\n return this.#queryClient.fetchQuery({\n ...options,\n queryFn: (context) =>\n this.#policy.execute(() => options.queryFn(context)),\n });\n }\n\n /**\n * Fetch a paginated query.\n *\n * @param options - The options defining the query. Note that although this\n * method wraps `fetchInfiniteQuery` from `@tanstack/query-core`, there are a\n * few differences:\n * - `queryKey` and `queryFn` are required\n * - `queryFn` must be a function, not a skip token\n * - `retry` and `retryDelay` are not available (retries can be customized\n * using the constructor's `servicePolicyOptions`).\n * @param pageParam - An optional page parameter.\n * @returns A page's worth of data (i.e. what `queryFn` returns). Note that\n * this is different from `@tanstack/query-core`'s `fetchInfiniteQuery`\n * method, which returns all pages.\n */\n protected async fetchInfiniteQuery<\n TQueryFnData extends Json,\n TError = DefaultError,\n TData extends TQueryFnData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam extends Json = Json,\n >(\n options: 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 },\n pageParam?: TPageParam,\n ): Promise<TData> {\n // A missing per-call `pageParam` means \"the first page\", which uses the\n // consumer's `initialPageParam`. A `null` initial param is preserved: `??`\n // only falls back when the per-call param itself is missing.\n const requestedPageParam = pageParam ?? options.initialPageParam;\n\n const query = this.#queryClient\n .getQueryCache()\n .find<TQueryFnData, TError, InfiniteData<TData, TPageParam>>({\n queryKey: options.queryKey,\n });\n\n // The first page (or a cold cache) goes through query-core's\n // `fetchInfiniteQuery`, which reuses the cached page while the query is\n // fresh. A cold jump starts the query at the requested page by using it as\n // the initial page param.\n if (\n !query?.state.data ||\n deepEqual(requestedPageParam, options.initialPageParam)\n ) {\n const result = await this.#queryClient.fetchInfiniteQuery({\n ...options,\n initialPageParam: requestedPageParam,\n queryFn: (context) =>\n this.#policy.execute(() => options.queryFn(context)),\n });\n\n return result.pages[0];\n }\n\n // A later page on an existing query. v5 no longer forwards an explicit page\n // param, so fetch it directly and merge it into the infinite cache,\n // appending the next page or prepending an earlier one.\n const { pages, pageParams } = query.state.data;\n const page = (await this.#policy.execute(() =>\n options.queryFn({\n client: this.#queryClient,\n queryKey: options.queryKey,\n signal: new AbortController().signal,\n pageParam: requestedPageParam,\n direction: 'forward',\n meta: options.meta,\n }),\n )) as TData;\n const nextPageParam = options.getNextPageParam(\n pages[pages.length - 1],\n pages,\n pageParams[pageParams.length - 1],\n pageParams,\n );\n this.#queryClient.setQueryData<InfiniteData<TData, TPageParam>>(\n options.queryKey,\n deepEqual(requestedPageParam, nextPageParam)\n ? {\n pages: [...pages, page],\n pageParams: [...pageParams, requestedPageParam],\n }\n : {\n pages: [page, ...pages],\n pageParams: [requestedPageParam, ...pageParams],\n },\n );\n\n return page;\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,mDAI6B;AAM7B,2CAA2D;AAE3D,qDAc8B;AAC9B,sEAAwC;AACxC,mCAAiD;AAEjD,sEAIkC;AAiDlC,+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;IAqC1B,YAAY,EACV,IAAI,EACJ,SAAS,EACT,iBAAiB,GAAG,EAAE,EACtB,aAAa,EACb,iBAAiB,GA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,KAAK,CAAC,CAAC;AAC1C,CAAC","sourcesContent":["import {\n Messenger,\n ActionConstraint,\n EventConstraint,\n} from '@metamask/messenger';\nimport type {\n StorageServiceGetItemAction,\n StorageServiceRemoveItemAction,\n StorageServiceSetItemAction,\n} from '@metamask/storage-service';\nimport { Duration, inMilliseconds } from '@metamask/utils';\nimport type { Json } from '@metamask/utils';\nimport {\n DefaultOptions,\n DehydratedState,\n FetchInfiniteQueryOptions,\n FetchQueryOptions,\n InfiniteData,\n InvalidateOptions,\n InvalidateQueryFilters,\n OmitKeyof,\n QueryClient,\n QueryClientConfig,\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';\n\n// Data service queries use the following format: ['ServiceActionName', ...params]\nexport type QueryKey = [string, ...Json[]];\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: (\n filters?: InvalidateQueryFilters<Json>,\n options?: InvalidateOptions,\n ) => Promise<void>;\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 Messenger<\n ServiceName,\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> {\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: ServiceMessenger;\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 * @returns The query results.\n */\n protected async fetchQuery<\n TQueryFnData extends Json,\n TError = unknown,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n >(\n options: WithRequired<\n OmitKeyof<\n FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'retry' | 'retryDelay'\n >,\n 'queryKey' | 'queryFn'\n >,\n ): Promise<TData> {\n return this.#queryClient.fetchQuery({\n ...options,\n queryFn: (context) =>\n this.#policy.execute(() => options.queryFn(context)),\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 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 = unknown,\n TData extends TQueryFnData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam extends Json = Json,\n >(\n options: WithRequired<\n OmitKeyof<\n FetchInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'retry' | 'retryDelay'\n >,\n 'queryKey' | 'queryFn'\n >,\n pageParam?: TPageParam,\n ): Promise<TData> {\n const cache = this.#queryClient.getQueryCache();\n\n const query = cache.find<TQueryFnData, TError, InfiniteData<TData>>({\n queryKey: options.queryKey,\n });\n\n if (!query?.state.data || pageParam === undefined) {\n const result = await this.#queryClient.fetchInfiniteQuery({\n ...options,\n queryFn: (context) =>\n this.#policy.execute(() =>\n options.queryFn({\n ...context,\n pageParam: context.pageParam ?? pageParam,\n }),\n ),\n });\n\n return result.pages[0];\n }\n\n const { pages } = query.state.data;\n const previous = options.getPreviousPageParam?.(pages[0], pages);\n\n const direction = deepEqual(pageParam, previous) ? 'backward' : 'forward';\n\n const result = await query.fetch(undefined, {\n meta: {\n fetchMore: {\n direction,\n pageParam,\n },\n },\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<Json>,\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,15 +1,8 @@
|
|
|
1
1
|
import { Messenger, ActionConstraint, EventConstraint } from "@metamask/messenger";
|
|
2
2
|
import type { Json } from "@metamask/utils";
|
|
3
|
-
import {
|
|
3
|
+
import { DehydratedState, FetchInfiniteQueryOptions, FetchQueryOptions, InvalidateOptions, InvalidateQueryFilters, OmitKeyof, QueryClientConfig, WithRequired } from "@tanstack/query-core";
|
|
4
4
|
import { CreateServicePolicyOptions } from "./createServicePolicy.cjs";
|
|
5
5
|
export type QueryKey = [string, ...Json[]];
|
|
6
|
-
/**
|
|
7
|
-
* The supertype of all messengers, scoped to a namespace.
|
|
8
|
-
*
|
|
9
|
-
* @template Namespace - The namespace for the messenger's own actions and
|
|
10
|
-
* events.
|
|
11
|
-
*/
|
|
12
|
-
export type BaseMessenger<Namespace extends string> = Messenger<Namespace, ActionConstraint, EventConstraint, any>;
|
|
13
6
|
export type DataServiceGranularCacheUpdatedPayload = {
|
|
14
7
|
type: 'added' | 'updated';
|
|
15
8
|
state: DehydratedState;
|
|
@@ -22,7 +15,7 @@ export type DataServiceCacheUpdatedPayload = DataServiceGranularCacheUpdatedPayl
|
|
|
22
15
|
};
|
|
23
16
|
export type DataServiceInvalidateQueriesAction<ServiceName extends string> = {
|
|
24
17
|
type: `${ServiceName}:invalidateQueries`;
|
|
25
|
-
handler:
|
|
18
|
+
handler: (filters?: InvalidateQueryFilters<Json>, options?: InvalidateOptions) => Promise<void>;
|
|
26
19
|
};
|
|
27
20
|
export type DataServiceActions<ServiceName extends string> = DataServiceInvalidateQueriesAction<ServiceName>;
|
|
28
21
|
export type DataServiceCacheUpdatedEvent<ServiceName extends string> = {
|
|
@@ -54,7 +47,7 @@ export type PersistenceConfiguration = {
|
|
|
54
47
|
*/
|
|
55
48
|
maxWriteDelay?: number;
|
|
56
49
|
};
|
|
57
|
-
export declare class BaseDataService<ServiceName extends string, ServiceMessenger extends
|
|
50
|
+
export declare class BaseDataService<ServiceName extends string, ServiceMessenger extends Messenger<ServiceName, ActionConstraint, EventConstraint, any>> {
|
|
58
51
|
#private;
|
|
59
52
|
readonly name: ServiceName;
|
|
60
53
|
protected messenger: ServiceMessenger;
|
|
@@ -68,36 +61,20 @@ export declare class BaseDataService<ServiceName extends string, ServiceMessenge
|
|
|
68
61
|
/**
|
|
69
62
|
* Fetch a query.
|
|
70
63
|
*
|
|
71
|
-
* @param options - The options defining the query.
|
|
72
|
-
*
|
|
73
|
-
* restrictions:
|
|
74
|
-
* - `queryKey` and `queryFn` are required
|
|
75
|
-
* - `queryFn` must be a function, not a skip token
|
|
76
|
-
* - `retry` and `retryDelay` are not available (retries can be customized
|
|
77
|
-
* using the constructor's `servicePolicyOptions`).
|
|
64
|
+
* @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.
|
|
65
|
+
* Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
|
|
78
66
|
* @returns The query results.
|
|
79
67
|
*/
|
|
80
|
-
protected fetchQuery<TQueryFnData extends Json, TError =
|
|
81
|
-
queryFn: QueryFunction<TQueryFnData, TQueryKey>;
|
|
82
|
-
}): Promise<TData>;
|
|
68
|
+
protected fetchQuery<TQueryFnData extends Json, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(options: WithRequired<OmitKeyof<FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>, 'retry' | 'retryDelay'>, 'queryKey' | 'queryFn'>): Promise<TData>;
|
|
83
69
|
/**
|
|
84
70
|
* Fetch a paginated query.
|
|
85
71
|
*
|
|
86
|
-
* @param options - The options defining the query.
|
|
87
|
-
*
|
|
88
|
-
* few differences:
|
|
89
|
-
* - `queryKey` and `queryFn` are required
|
|
90
|
-
* - `queryFn` must be a function, not a skip token
|
|
91
|
-
* - `retry` and `retryDelay` are not available (retries can be customized
|
|
92
|
-
* using the constructor's `servicePolicyOptions`).
|
|
72
|
+
* @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.
|
|
73
|
+
* Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
|
|
93
74
|
* @param pageParam - An optional page parameter.
|
|
94
|
-
* @returns
|
|
95
|
-
* this is different from `@tanstack/query-core`'s `fetchInfiniteQuery`
|
|
96
|
-
* method, which returns all pages.
|
|
75
|
+
* @returns The query result, exclusively the requested page is returned.
|
|
97
76
|
*/
|
|
98
|
-
protected fetchInfiniteQuery<TQueryFnData extends Json, TError =
|
|
99
|
-
queryFn: QueryFunction<TQueryFnData, TQueryKey, TPageParam>;
|
|
100
|
-
}, pageParam?: TPageParam): Promise<TData>;
|
|
77
|
+
protected fetchInfiniteQuery<TQueryFnData extends Json, TError = unknown, TData extends TQueryFnData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, TPageParam extends Json = Json>(options: WithRequired<OmitKeyof<FetchInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey>, 'retry' | 'retryDelay'>, 'queryKey' | 'queryFn'>, pageParam?: TPageParam): Promise<TData>;
|
|
101
78
|
/**
|
|
102
79
|
* Invalidate queries serviced by this data service.
|
|
103
80
|
*
|
|
@@ -105,7 +82,7 @@ export declare class BaseDataService<ServiceName extends string, ServiceMessenge
|
|
|
105
82
|
* @param options - Additional optional options for query invalidations.
|
|
106
83
|
* @returns Nothing.
|
|
107
84
|
*/
|
|
108
|
-
invalidateQueries(filters?: InvalidateQueryFilters<
|
|
85
|
+
invalidateQueries(filters?: InvalidateQueryFilters<Json>, options?: InvalidateOptions): Promise<void>;
|
|
109
86
|
/**
|
|
110
87
|
* Initialize the service, rehydrating the cache with persisted data if possible.
|
|
111
88
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseDataService.d.cts","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,gBAAgB,EAChB,eAAe,EAChB,4BAA4B;AAO7B,OAAO,KAAK,EAAE,IAAI,EAAE,wBAAwB;AAC5C,OAAO,
|
|
1
|
+
{"version":3,"file":"BaseDataService.d.cts","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,gBAAgB,EAChB,eAAe,EAChB,4BAA4B;AAO7B,OAAO,KAAK,EAAE,IAAI,EAAE,wBAAwB;AAC5C,OAAO,EAEL,eAAe,EACf,yBAAyB,EACzB,iBAAiB,EAEjB,iBAAiB,EACjB,sBAAsB,EACtB,SAAS,EAET,iBAAiB,EACjB,YAAY,EAGb,6BAA6B;AAI9B,OAAO,EAEL,0BAA0B,EAE3B,kCAAiC;AAGlC,MAAM,MAAM,QAAQ,GAAG,CAAC,MAAM,EAAE,GAAG,IAAI,EAAE,CAAC,CAAC;AAE3C,MAAM,MAAM,sCAAsC,GAC9C;IAAE,IAAI,EAAE,OAAO,GAAG,SAAS,CAAC;IAAC,KAAK,EAAE,eAAe,CAAA;CAAE,GACrD;IACE,IAAI,EAAE,SAAS,CAAC;IAChB,KAAK,EAAE,IAAI,CAAC;CACb,CAAC;AAEN,MAAM,MAAM,8BAA8B,GACxC,sCAAsC,GAAG;IACvC,IAAI,EAAE,MAAM,CAAC;CACd,CAAC;AAIJ,MAAM,MAAM,kCAAkC,CAAC,WAAW,SAAS,MAAM,IAAI;IAC3E,I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import { Messenger, ActionConstraint, EventConstraint } from "@metamask/messenger";
|
|
2
2
|
import type { Json } from "@metamask/utils";
|
|
3
|
-
import {
|
|
3
|
+
import { DehydratedState, FetchInfiniteQueryOptions, FetchQueryOptions, InvalidateOptions, InvalidateQueryFilters, OmitKeyof, QueryClientConfig, WithRequired } from "@tanstack/query-core";
|
|
4
4
|
import { CreateServicePolicyOptions } from "./createServicePolicy.mjs";
|
|
5
5
|
export type QueryKey = [string, ...Json[]];
|
|
6
|
-
/**
|
|
7
|
-
* The supertype of all messengers, scoped to a namespace.
|
|
8
|
-
*
|
|
9
|
-
* @template Namespace - The namespace for the messenger's own actions and
|
|
10
|
-
* events.
|
|
11
|
-
*/
|
|
12
|
-
export type BaseMessenger<Namespace extends string> = Messenger<Namespace, ActionConstraint, EventConstraint, any>;
|
|
13
6
|
export type DataServiceGranularCacheUpdatedPayload = {
|
|
14
7
|
type: 'added' | 'updated';
|
|
15
8
|
state: DehydratedState;
|
|
@@ -22,7 +15,7 @@ export type DataServiceCacheUpdatedPayload = DataServiceGranularCacheUpdatedPayl
|
|
|
22
15
|
};
|
|
23
16
|
export type DataServiceInvalidateQueriesAction<ServiceName extends string> = {
|
|
24
17
|
type: `${ServiceName}:invalidateQueries`;
|
|
25
|
-
handler:
|
|
18
|
+
handler: (filters?: InvalidateQueryFilters<Json>, options?: InvalidateOptions) => Promise<void>;
|
|
26
19
|
};
|
|
27
20
|
export type DataServiceActions<ServiceName extends string> = DataServiceInvalidateQueriesAction<ServiceName>;
|
|
28
21
|
export type DataServiceCacheUpdatedEvent<ServiceName extends string> = {
|
|
@@ -54,7 +47,7 @@ export type PersistenceConfiguration = {
|
|
|
54
47
|
*/
|
|
55
48
|
maxWriteDelay?: number;
|
|
56
49
|
};
|
|
57
|
-
export declare class BaseDataService<ServiceName extends string, ServiceMessenger extends
|
|
50
|
+
export declare class BaseDataService<ServiceName extends string, ServiceMessenger extends Messenger<ServiceName, ActionConstraint, EventConstraint, any>> {
|
|
58
51
|
#private;
|
|
59
52
|
readonly name: ServiceName;
|
|
60
53
|
protected messenger: ServiceMessenger;
|
|
@@ -68,36 +61,20 @@ export declare class BaseDataService<ServiceName extends string, ServiceMessenge
|
|
|
68
61
|
/**
|
|
69
62
|
* Fetch a query.
|
|
70
63
|
*
|
|
71
|
-
* @param options - The options defining the query.
|
|
72
|
-
*
|
|
73
|
-
* restrictions:
|
|
74
|
-
* - `queryKey` and `queryFn` are required
|
|
75
|
-
* - `queryFn` must be a function, not a skip token
|
|
76
|
-
* - `retry` and `retryDelay` are not available (retries can be customized
|
|
77
|
-
* using the constructor's `servicePolicyOptions`).
|
|
64
|
+
* @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.
|
|
65
|
+
* Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
|
|
78
66
|
* @returns The query results.
|
|
79
67
|
*/
|
|
80
|
-
protected fetchQuery<TQueryFnData extends Json, TError =
|
|
81
|
-
queryFn: QueryFunction<TQueryFnData, TQueryKey>;
|
|
82
|
-
}): Promise<TData>;
|
|
68
|
+
protected fetchQuery<TQueryFnData extends Json, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(options: WithRequired<OmitKeyof<FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>, 'retry' | 'retryDelay'>, 'queryKey' | 'queryFn'>): Promise<TData>;
|
|
83
69
|
/**
|
|
84
70
|
* Fetch a paginated query.
|
|
85
71
|
*
|
|
86
|
-
* @param options - The options defining the query.
|
|
87
|
-
*
|
|
88
|
-
* few differences:
|
|
89
|
-
* - `queryKey` and `queryFn` are required
|
|
90
|
-
* - `queryFn` must be a function, not a skip token
|
|
91
|
-
* - `retry` and `retryDelay` are not available (retries can be customized
|
|
92
|
-
* using the constructor's `servicePolicyOptions`).
|
|
72
|
+
* @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.
|
|
73
|
+
* Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
|
|
93
74
|
* @param pageParam - An optional page parameter.
|
|
94
|
-
* @returns
|
|
95
|
-
* this is different from `@tanstack/query-core`'s `fetchInfiniteQuery`
|
|
96
|
-
* method, which returns all pages.
|
|
75
|
+
* @returns The query result, exclusively the requested page is returned.
|
|
97
76
|
*/
|
|
98
|
-
protected fetchInfiniteQuery<TQueryFnData extends Json, TError =
|
|
99
|
-
queryFn: QueryFunction<TQueryFnData, TQueryKey, TPageParam>;
|
|
100
|
-
}, pageParam?: TPageParam): Promise<TData>;
|
|
77
|
+
protected fetchInfiniteQuery<TQueryFnData extends Json, TError = unknown, TData extends TQueryFnData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, TPageParam extends Json = Json>(options: WithRequired<OmitKeyof<FetchInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey>, 'retry' | 'retryDelay'>, 'queryKey' | 'queryFn'>, pageParam?: TPageParam): Promise<TData>;
|
|
101
78
|
/**
|
|
102
79
|
* Invalidate queries serviced by this data service.
|
|
103
80
|
*
|
|
@@ -105,7 +82,7 @@ export declare class BaseDataService<ServiceName extends string, ServiceMessenge
|
|
|
105
82
|
* @param options - Additional optional options for query invalidations.
|
|
106
83
|
* @returns Nothing.
|
|
107
84
|
*/
|
|
108
|
-
invalidateQueries(filters?: InvalidateQueryFilters<
|
|
85
|
+
invalidateQueries(filters?: InvalidateQueryFilters<Json>, options?: InvalidateOptions): Promise<void>;
|
|
109
86
|
/**
|
|
110
87
|
* Initialize the service, rehydrating the cache with persisted data if possible.
|
|
111
88
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseDataService.d.mts","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,gBAAgB,EAChB,eAAe,EAChB,4BAA4B;AAO7B,OAAO,KAAK,EAAE,IAAI,EAAE,wBAAwB;AAC5C,OAAO,
|
|
1
|
+
{"version":3,"file":"BaseDataService.d.mts","sour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,CACvB,EACD,UAAU,GAAG,SAAS,CACvB,GACA,OAAO,CAAC,KAAK,CAAC;IAQjB;;;;;;;OAOG;cACa,kBAAkB,CAChC,YAAY,SAAS,IAAI,EACzB,MAAM,GAAG,OAAO,EAChB,KAAK,SAAS,YAAY,GAAG,YAAY,EACzC,SAAS,SAAS,QAAQ,GAAG,QAAQ,EACrC,UAAU,SAAS,IAAI,GAAG,IAAI,EAE9B,OAAO,EAAE,YAAY,CACnB,SAAS,CACP,yBAAyB,CAAC,YAAY,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,CAAC,EACjE,OAAO,GAAG,YAAY,CACvB,EACD,UAAU,GAAG,SAAS,CACvB,EACD,SAAS,CAAC,EAAE,UAAU,GACrB,OAAO,CAAC,KAAK,CAAC;IA2CjB;;;;;;OAMG;IACG,iBAAiB,CACrB,OAAO,CAAC,EAAE,sBAAsB,CAAC,IAAI,CAAC,EACtC,OAAO,CAAC,EAAE,iBAAiB,GAC1B,OAAO,CAAC,IAAI,CAAC;IAIhB;;OAEG;IACH,IAAI,IAAI,IAAI;IAOZ;;;OAGG;IACH,OAAO,IAAI,IAAI;CA2GhB"}
|
package/dist/BaseDataService.mjs
CHANGED
|
@@ -85,13 +85,8 @@ export class BaseDataService {
|
|
|
85
85
|
/**
|
|
86
86
|
* Fetch a query.
|
|
87
87
|
*
|
|
88
|
-
* @param options - The options defining the query.
|
|
89
|
-
*
|
|
90
|
-
* restrictions:
|
|
91
|
-
* - `queryKey` and `queryFn` are required
|
|
92
|
-
* - `queryFn` must be a function, not a skip token
|
|
93
|
-
* - `retry` and `retryDelay` are not available (retries can be customized
|
|
94
|
-
* using the constructor's `servicePolicyOptions`).
|
|
88
|
+
* @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.
|
|
89
|
+
* Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
|
|
95
90
|
* @returns The query results.
|
|
96
91
|
*/
|
|
97
92
|
async fetchQuery(options) {
|
|
@@ -103,64 +98,39 @@ export class BaseDataService {
|
|
|
103
98
|
/**
|
|
104
99
|
* Fetch a paginated query.
|
|
105
100
|
*
|
|
106
|
-
* @param options - The options defining the query.
|
|
107
|
-
*
|
|
108
|
-
* few differences:
|
|
109
|
-
* - `queryKey` and `queryFn` are required
|
|
110
|
-
* - `queryFn` must be a function, not a skip token
|
|
111
|
-
* - `retry` and `retryDelay` are not available (retries can be customized
|
|
112
|
-
* using the constructor's `servicePolicyOptions`).
|
|
101
|
+
* @param options - The options defining the query. Keep in mind that `queryKey` and `queryFn` are required when using data services.
|
|
102
|
+
* Additionally `retry` and `retryDelay` are not available, retries can be customized using the `servicePolicyOptions`.
|
|
113
103
|
* @param pageParam - An optional page parameter.
|
|
114
|
-
* @returns
|
|
115
|
-
* this is different from `@tanstack/query-core`'s `fetchInfiniteQuery`
|
|
116
|
-
* method, which returns all pages.
|
|
104
|
+
* @returns The query result, exclusively the requested page is returned.
|
|
117
105
|
*/
|
|
118
106
|
async fetchInfiniteQuery(options, pageParam) {
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
// only falls back when the per-call param itself is missing.
|
|
122
|
-
const requestedPageParam = pageParam ?? options.initialPageParam;
|
|
123
|
-
const query = __classPrivateFieldGet(this, _BaseDataService_queryClient, "f")
|
|
124
|
-
.getQueryCache()
|
|
125
|
-
.find({
|
|
107
|
+
const cache = __classPrivateFieldGet(this, _BaseDataService_queryClient, "f").getQueryCache();
|
|
108
|
+
const query = cache.find({
|
|
126
109
|
queryKey: options.queryKey,
|
|
127
110
|
});
|
|
128
|
-
|
|
129
|
-
// `fetchInfiniteQuery`, which reuses the cached page while the query is
|
|
130
|
-
// fresh. A cold jump starts the query at the requested page by using it as
|
|
131
|
-
// the initial page param.
|
|
132
|
-
if (!query?.state.data ||
|
|
133
|
-
deepEqual(requestedPageParam, options.initialPageParam)) {
|
|
111
|
+
if (!query?.state.data || pageParam === undefined) {
|
|
134
112
|
const result = await __classPrivateFieldGet(this, _BaseDataService_queryClient, "f").fetchInfiniteQuery({
|
|
135
113
|
...options,
|
|
136
|
-
|
|
137
|
-
|
|
114
|
+
queryFn: (context) => __classPrivateFieldGet(this, _BaseDataService_policy, "f").execute(() => options.queryFn({
|
|
115
|
+
...context,
|
|
116
|
+
pageParam: context.pageParam ?? pageParam,
|
|
117
|
+
})),
|
|
138
118
|
});
|
|
139
119
|
return result.pages[0];
|
|
140
120
|
}
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
const
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
__classPrivateFieldGet(this, _BaseDataService_queryClient, "f").setQueryData(options.queryKey, deepEqual(requestedPageParam, nextPageParam)
|
|
155
|
-
? {
|
|
156
|
-
pages: [...pages, page],
|
|
157
|
-
pageParams: [...pageParams, requestedPageParam],
|
|
158
|
-
}
|
|
159
|
-
: {
|
|
160
|
-
pages: [page, ...pages],
|
|
161
|
-
pageParams: [requestedPageParam, ...pageParams],
|
|
162
|
-
});
|
|
163
|
-
return page;
|
|
121
|
+
const { pages } = query.state.data;
|
|
122
|
+
const previous = options.getPreviousPageParam?.(pages[0], pages);
|
|
123
|
+
const direction = deepEqual(pageParam, previous) ? 'backward' : 'forward';
|
|
124
|
+
const result = await query.fetch(undefined, {
|
|
125
|
+
meta: {
|
|
126
|
+
fetchMore: {
|
|
127
|
+
direction,
|
|
128
|
+
pageParam,
|
|
129
|
+
},
|
|
130
|
+
},
|
|
131
|
+
});
|
|
132
|
+
const pageIndex = result.pageParams.findIndex((param) => deepEqual(param, pageParam));
|
|
133
|
+
return result.pages[pageIndex];
|
|
164
134
|
}
|
|
165
135
|
/**
|
|
166
136
|
* Invalidate queries serviced by this data service.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseDataService.mjs","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"m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,CAAC,OAAO,CAAC,MAAM,KAAK,CAAC,IAAI,KAAK,CAAC,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC/D,MAAM,uBAAA,IAAI,0CAAmB,CAAC,IAAI,CAChC,2BAA2B,EAC3B,IAAI,CAAC,IAAI,EACT,mBAAmB,CACpB,CAAC;QACF,OAAO;IACT,CAAC;IAED,MAAM,KAAK,GAAmB;QAC5B,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;QACrB,KAAK;KACN,CAAC;IAEF,MAAM,uBAAA,IAAI,0CAAmB,CAAC,IAAI,CAChC,wBAAwB,EACxB,IAAI,CAAC,IAAI,EACT,mBAAmB,EACnB,KAAwB,CACzB,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,KAAK;IACH,IAAI,CAAC,uBAAA,IAAI,0CAAmB,EAAE,CAAC;QAC7B,OAAO;IACT,CAAC;IAED,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,GAAG,MAAM,uBAAA,IAAI,0CAAmB,CAAC,IAAI,CACjE,wBAAwB,EACxB,IAAI,CAAC,IAAI,EACT,mBAAmB,CACpB,CAAC;IAEF,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,OAAO;IACT,CAAC;IAED,MAAM,KAAK,GAAG,YAAyC,CAAC;IAExD,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,SAAS,IAAI,uBAAA,IAAI,0CAAmB,CAAC,MAAM,EAAE,CAAC;QACnE,MAAM,uBAAA,IAAI,0CAAmB,CAAC,IAAI,CAChC,2BAA2B,EAC3B,IAAI,CAAC,IAAI,EACT,mBAAmB,CACpB,CAAC;QACF,OAAO;IACT,CAAC;IAED,OAAO,CAAC,uBAAA,IAAI,oCAAa,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;AAC1C,CAAC","sourcesContent":["import {\n Messenger,\n ActionConstraint,\n EventConstraint,\n} from '@metamask/messenger';\nimport type {\n StorageServiceGetItemAction,\n StorageServiceRemoveItemAction,\n StorageServiceSetItemAction,\n} from '@metamask/storage-service';\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';\n\n// Data service queries use the following format: ['ServiceActionName', ...params]\nexport type QueryKey = [string, ...Json[]];\n\n/**\n * The supertype of all messengers, scoped to a namespace.\n *\n * @template Namespace - The namespace for the messenger's own actions and\n * events.\n */\nexport type BaseMessenger<Namespace extends string> = Messenger<\n Namespace,\n ActionConstraint,\n EventConstraint,\n // Use `any` to allow any parent to be set. `any` is harmless in a type constraint anyway,\n // it's the one totally safe place to use it.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any\n>;\n\nexport type DataServiceGranularCacheUpdatedPayload =\n | { type: 'added' | 'updated'; state: DehydratedState }\n | {\n type: 'removed';\n state: null;\n };\n\nexport type DataServiceCacheUpdatedPayload =\n DataServiceGranularCacheUpdatedPayload & {\n hash: string;\n };\n\ntype CacheUpdatedType = DataServiceCacheUpdatedPayload['type'];\n\nexport type DataServiceInvalidateQueriesAction<ServiceName extends string> = {\n type: `${ServiceName}:invalidateQueries`;\n handler: BaseDataService<\n ServiceName,\n BaseMessenger<ServiceName>\n >['invalidateQueries'];\n};\n\nexport type DataServiceActions<ServiceName extends string> =\n DataServiceInvalidateQueriesAction<ServiceName>;\n\ntype DataServiceAllowedActions =\n | StorageServiceGetItemAction\n | StorageServiceSetItemAction\n | StorageServiceRemoveItemAction;\n\nexport type DataServiceCacheUpdatedEvent<ServiceName extends string> = {\n type: `${ServiceName}:cacheUpdated`;\n payload: [DataServiceCacheUpdatedPayload];\n};\n\nexport type DataServiceGranularCacheUpdatedEvent<ServiceName extends string> = {\n type: `${ServiceName}:cacheUpdated:${string}`;\n payload: [DataServiceGranularCacheUpdatedPayload];\n};\n\nexport type DataServiceEvents<ServiceName extends string> =\n | DataServiceCacheUpdatedEvent<ServiceName>\n | DataServiceGranularCacheUpdatedEvent<ServiceName>;\n\n// Defaults to apply to all data service queries if no default option specified\nconst QUERY_CLIENT_DEFAULTS: DefaultOptions = {\n queries: {\n retry: false,\n staleTime: inMilliseconds(1, Duration.Minute),\n },\n};\n\nexport const STORAGE_SERVICE_KEY = 'cache';\n\n/**\n * Options for persistence configuration.\n */\nexport type PersistenceConfiguration = {\n /**\n * The maximum age before the cache is treated as expired in milliseconds.\n * This is relevant for rehydrating the state during initialization,\n * if the cached state is too old it will be discarded.\n */\n maxAge: number;\n /**\n * The number of milliseconds to wait before triggering persistence following a cache update.\n */\n writeDelay?: number;\n /**\n * The maximum number of milliseconds to wait between persistence writes.\n */\n maxWriteDelay?: number;\n};\n\ntype PersistedCache = {\n state: DehydratedState;\n timestamp: number;\n};\n\nexport class BaseDataService<\n ServiceName extends string,\n ServiceMessenger extends BaseMessenger<ServiceName>,\n> {\n public readonly name: ServiceName;\n\n readonly #messenger: Messenger<\n ServiceName,\n DataServiceActions<ServiceName>,\n DataServiceEvents<ServiceName>\n >;\n\n readonly #externalMessenger: Messenger<\n ServiceName,\n DataServiceAllowedActions\n >;\n\n protected messenger: ServiceMessenger;\n\n readonly #policy: ServicePolicy;\n\n readonly #queryClient: QueryClient;\n\n readonly #queryCacheUnsubscribe: () => void;\n\n readonly #debouncedPersist?: DebouncedFunc<() => void>;\n\n readonly #persistenceConfig?: PersistenceConfiguration;\n\n constructor({\n name,\n messenger,\n queryClientConfig = {},\n policyOptions,\n persistenceConfig,\n }: {\n name: ServiceName;\n messenger: ServiceMessenger;\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. Note that although this\n * method wraps `fetchQuery` from `@tanstack/query-core`, there are a few\n * restrictions:\n * - `queryKey` and `queryFn` are required\n * - `queryFn` must be a function, not a skip token\n * - `retry` and `retryDelay` are not available (retries can be customized\n * using the constructor's `servicePolicyOptions`).\n * @returns The query results.\n */\n protected async fetchQuery<\n TQueryFnData extends Json,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n >(\n options: WithRequired<\n OmitKeyof<\n FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'retry' | 'retryDelay' | 'queryFn'\n >,\n 'queryKey'\n > & {\n // @tanstack/query-core's fetchQuery function accepts a \"skip\" token, but\n // data services always provide a concrete query function.\n queryFn: QueryFunction<TQueryFnData, TQueryKey>;\n },\n ): Promise<TData> {\n return this.#queryClient.fetchQuery({\n ...options,\n queryFn: (context) =>\n this.#policy.execute(() => options.queryFn(context)),\n });\n }\n\n /**\n * Fetch a paginated query.\n *\n * @param options - The options defining the query. Note that although this\n * method wraps `fetchInfiniteQuery` from `@tanstack/query-core`, there are a\n * few differences:\n * - `queryKey` and `queryFn` are required\n * - `queryFn` must be a function, not a skip token\n * - `retry` and `retryDelay` are not available (retries can be customized\n * using the constructor's `servicePolicyOptions`).\n * @param pageParam - An optional page parameter.\n * @returns A page's worth of data (i.e. what `queryFn` returns). Note that\n * this is different from `@tanstack/query-core`'s `fetchInfiniteQuery`\n * method, which returns all pages.\n */\n protected async fetchInfiniteQuery<\n TQueryFnData extends Json,\n TError = DefaultError,\n TData extends TQueryFnData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam extends Json = Json,\n >(\n options: 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 },\n pageParam?: TPageParam,\n ): Promise<TData> {\n // A missing per-call `pageParam` means \"the first page\", which uses the\n // consumer's `initialPageParam`. A `null` initial param is preserved: `??`\n // only falls back when the per-call param itself is missing.\n const requestedPageParam = pageParam ?? options.initialPageParam;\n\n const query = this.#queryClient\n .getQueryCache()\n .find<TQueryFnData, TError, InfiniteData<TData, TPageParam>>({\n queryKey: options.queryKey,\n });\n\n // The first page (or a cold cache) goes through query-core's\n // `fetchInfiniteQuery`, which reuses the cached page while the query is\n // fresh. A cold jump starts the query at the requested page by using it as\n // the initial page param.\n if (\n !query?.state.data ||\n deepEqual(requestedPageParam, options.initialPageParam)\n ) {\n const result = await this.#queryClient.fetchInfiniteQuery({\n ...options,\n initialPageParam: requestedPageParam,\n queryFn: (context) =>\n this.#policy.execute(() => options.queryFn(context)),\n });\n\n return result.pages[0];\n }\n\n // A later page on an existing query. v5 no longer forwards an explicit page\n // param, so fetch it directly and merge it into the infinite cache,\n // appending the next page or prepending an earlier one.\n const { pages, pageParams } = query.state.data;\n const page = (await this.#policy.execute(() =>\n options.queryFn({\n client: this.#queryClient,\n queryKey: options.queryKey,\n signal: new AbortController().signal,\n pageParam: requestedPageParam,\n direction: 'forward',\n meta: options.meta,\n }),\n )) as TData;\n const nextPageParam = options.getNextPageParam(\n pages[pages.length - 1],\n pages,\n pageParams[pageParams.length - 1],\n pageParams,\n );\n this.#queryClient.setQueryData<InfiniteData<TData, TPageParam>>(\n options.queryKey,\n deepEqual(requestedPageParam, nextPageParam)\n ? {\n pages: [...pages, page],\n pageParams: [...pageParams, requestedPageParam],\n }\n : {\n pages: [page, ...pages],\n pageParams: [requestedPageParam, ...pageParams],\n },\n );\n\n return page;\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,EAGV,4BAA4B;AAM7B,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,wBAAwB;AAE3D,OAAO,EASL,WAAW,EAGX,SAAS,EACT,OAAO,EACR,6BAA6B;AAC9B,OAAO,UAAS,wBAAwB;;;;AAGxC,OAAO,EACL,mBAAmB,EAGpB,kCAAiC;AAiDlC,+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;IAqC1B,YAAY,EACV,IAAI,EACJ,SAAS,EACT,iBAAiB,GAAG,EAAE,EACtB,aAAa,EACb,iBAAiB,GAOlB;;QAnCQ,6CAIP;QAEO,qDAGP;QAIO,0CAAuB;QAEvB,+CAA0B;QAE1B,yDAAmC;QAEnC,oDAA8C;QAE9C,qDAA8C;QAerD,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QAEjB,2EAA2E;QAC3E,kFAAkF;QAClF,yDAAyD;QACzD,6FAA6F;QAC7F,uBAAA,IAAI,8BAAc,SAIjB,MAAA,CAAC;QACF,uBAAA,IAAI,sCAAsB,SAGzB,MAAA,CAAC;QACF,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAE3B,uBAAA,IAAI,gCAAgB,I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AM,uBAAA,IAAI,0CAAmB,CAAC,IAAI,CAChC,wBAAwB,EACxB,IAAI,CAAC,IAAI,EACT,mBAAmB,EACnB,KAAwB,CACzB,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,KAAK;IACH,IAAI,CAAC,uBAAA,IAAI,0CAAmB,EAAE,CAAC;QAC7B,OAAO;IACT,CAAC;IAED,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,GAAG,MAAM,uBAAA,IAAI,0CAAmB,CAAC,IAAI,CACjE,wBAAwB,EACxB,IAAI,CAAC,IAAI,EACT,mBAAmB,CACpB,CAAC;IAEF,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,OAAO;IACT,CAAC;IAED,MAAM,KAAK,GAAG,YAAyC,CAAC;IAExD,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,SAAS,IAAI,uBAAA,IAAI,0CAAmB,CAAC,MAAM,EAAE,CAAC;QACnE,MAAM,uBAAA,IAAI,0CAAmB,CAAC,IAAI,CAChC,2BAA2B,EAC3B,IAAI,CAAC,IAAI,EACT,mBAAmB,CACpB,CAAC;QACF,OAAO;IACT,CAAC;IAED,OAAO,CAAC,uBAAA,IAAI,oCAAa,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;AAC1C,CAAC","sourcesContent":["import {\n Messenger,\n ActionConstraint,\n EventConstraint,\n} from '@metamask/messenger';\nimport type {\n StorageServiceGetItemAction,\n StorageServiceRemoveItemAction,\n StorageServiceSetItemAction,\n} from '@metamask/storage-service';\nimport { Duration, inMilliseconds } from '@metamask/utils';\nimport type { Json } from '@metamask/utils';\nimport {\n DefaultOptions,\n DehydratedState,\n FetchInfiniteQueryOptions,\n FetchQueryOptions,\n InfiniteData,\n InvalidateOptions,\n InvalidateQueryFilters,\n OmitKeyof,\n QueryClient,\n QueryClientConfig,\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';\n\n// Data service queries use the following format: ['ServiceActionName', ...params]\nexport type QueryKey = [string, ...Json[]];\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: (\n filters?: InvalidateQueryFilters<Json>,\n options?: InvalidateOptions,\n ) => Promise<void>;\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 Messenger<\n ServiceName,\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> {\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: ServiceMessenger;\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 * @returns The query results.\n */\n protected async fetchQuery<\n TQueryFnData extends Json,\n TError = unknown,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n >(\n options: WithRequired<\n OmitKeyof<\n FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'retry' | 'retryDelay'\n >,\n 'queryKey' | 'queryFn'\n >,\n ): Promise<TData> {\n return this.#queryClient.fetchQuery({\n ...options,\n queryFn: (context) =>\n this.#policy.execute(() => options.queryFn(context)),\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 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 = unknown,\n TData extends TQueryFnData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam extends Json = Json,\n >(\n options: WithRequired<\n OmitKeyof<\n FetchInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'retry' | 'retryDelay'\n >,\n 'queryKey' | 'queryFn'\n >,\n pageParam?: TPageParam,\n ): Promise<TData> {\n const cache = this.#queryClient.getQueryCache();\n\n const query = cache.find<TQueryFnData, TError, InfiniteData<TData>>({\n queryKey: options.queryKey,\n });\n\n if (!query?.state.data || pageParam === undefined) {\n const result = await this.#queryClient.fetchInfiniteQuery({\n ...options,\n queryFn: (context) =>\n this.#policy.execute(() =>\n options.queryFn({\n ...context,\n pageParam: context.pageParam ?? pageParam,\n }),\n ),\n });\n\n return result.pages[0];\n }\n\n const { pages } = query.state.data;\n const previous = options.getPreviousPageParam?.(pages[0], pages);\n\n const direction = deepEqual(pageParam, previous) ? 'backward' : 'forward';\n\n const result = await query.fetch(undefined, {\n meta: {\n fetchMore: {\n direction,\n pageParam,\n },\n },\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<Json>,\n options?: InvalidateOptions,\n ): Promise<void> {\n return this.#queryClient.invalidateQueries(filters, options);\n }\n\n /**\n * Initialize the service, rehydrating the cache with persisted data if possible.\n */\n init(): void {\n this.#loadCache().catch(\n /* istanbul ignore next */\n (error) => this.#messenger.captureException?.(error),\n );\n }\n\n /**\n * Prepares the service for garbage collection. This should be extended\n * by any subclasses to clean up any additional connections or events.\n */\n destroy(): void {\n this.#debouncedPersist?.cancel();\n this.#queryCacheUnsubscribe();\n this.#queryClient.clear();\n this.messenger.clearSubscriptions();\n this.messenger.clearActions();\n }\n\n /**\n * Publish `cacheUpdated` events when a given query changes.\n *\n * @param hash The hash of the query.\n * @param type The type of cache update.\n */\n #publishCacheUpdate(hash: string, type: CacheUpdatedType): void {\n const state =\n type === 'added' || type === 'updated'\n ? dehydrate(this.#queryClient, {\n shouldDehydrateQuery: (query) => query.queryHash === hash,\n })\n : null;\n\n this.#messenger.publish(\n `${this.name}:cacheUpdated` as const,\n {\n type,\n hash,\n state,\n } as DataServiceCacheUpdatedPayload,\n );\n\n this.#messenger.publish(\n `${this.name}:cacheUpdated:${hash}` as const,\n {\n type,\n state,\n } as DataServiceGranularCacheUpdatedPayload,\n );\n }\n\n /**\n * Persist the query client cache using the StorageService, if the cache is not empty.\n *\n * @returns Nothing.\n */\n async #persistCache(): Promise<void> {\n const state = dehydrate(this.#queryClient, {\n // This is the default, but we specify it to be explicit.\n shouldDehydrateQuery: (query) => query.state.status === 'success',\n });\n\n if (state.queries.length === 0 && state.mutations.length === 0) {\n await this.#externalMessenger.call(\n 'StorageService:removeItem',\n this.name,\n STORAGE_SERVICE_KEY,\n );\n return;\n }\n\n const cache: PersistedCache = {\n timestamp: Date.now(),\n state,\n };\n\n await this.#externalMessenger.call(\n 'StorageService:setItem',\n this.name,\n STORAGE_SERVICE_KEY,\n cache as unknown as Json,\n );\n }\n\n /**\n * Load the query client cache from the StorageService, if persistence is configured\n * and the persisted cache is not expired.\n *\n * @returns Nothing.\n */\n async #loadCache(): Promise<void> {\n if (!this.#persistenceConfig) {\n return;\n }\n\n const { result: untypedCache } = await this.#externalMessenger.call(\n 'StorageService:getItem',\n this.name,\n STORAGE_SERVICE_KEY,\n );\n\n if (!untypedCache) {\n return;\n }\n\n const cache = untypedCache as unknown as PersistedCache;\n\n if (Date.now() - cache.timestamp >= this.#persistenceConfig.maxAge) {\n await this.#externalMessenger.call(\n 'StorageService:removeItem',\n this.name,\n STORAGE_SERVICE_KEY,\n );\n return;\n }\n\n hydrate(this.#queryClient, cache.state);\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask-previews/base-data-service",
|
|
3
|
-
"version": "0.1.3-preview-
|
|
3
|
+
"version": "0.1.3-preview-c2ef75d18",
|
|
4
4
|
"description": "Provides utilities for building data services",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"Ethereum",
|
|
@@ -59,7 +59,7 @@
|
|
|
59
59
|
"@metamask/messenger": "^2.0.0",
|
|
60
60
|
"@metamask/storage-service": "^1.0.2",
|
|
61
61
|
"@metamask/utils": "^11.11.0",
|
|
62
|
-
"@tanstack/query-core": "^
|
|
62
|
+
"@tanstack/query-core": "^4.43.0",
|
|
63
63
|
"cockatiel": "^3.1.2",
|
|
64
64
|
"fast-deep-equal": "^3.1.3",
|
|
65
65
|
"lodash": "^4.17.21"
|