@metamask-previews/base-data-service 2.0.0-preview-6acac7d → 2.0.0-preview-df2073e
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
CHANGED
|
@@ -13,7 +13,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
13
13
|
- These kinds of requests are never retried, unlike queries.
|
|
14
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
15
|
- A `MutationKey` type is also available.
|
|
16
|
-
- Add protected `cancelQueries` so subclasses can abort in-flight reads before a forced refresh ([#10454](https://github.com/MetaMask/core/pull/10454))
|
|
17
16
|
|
|
18
17
|
### Changed
|
|
19
18
|
|
|
@@ -2,7 +2,7 @@ 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, MutationOptions, OmitKeyof, QueryClientConfig,
|
|
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.js';
|
|
7
7
|
/**
|
|
8
8
|
* Data service mutations and queries use the following format:
|
|
@@ -131,17 +131,6 @@ export declare class BaseDataService<ServiceName extends string, ServiceMessenge
|
|
|
131
131
|
* @returns Nothing.
|
|
132
132
|
*/
|
|
133
133
|
invalidateQueries(filters?: InvalidateQueryFilters<QueryKey>, options?: InvalidateOptions): Promise<void>;
|
|
134
|
-
/**
|
|
135
|
-
* Cancel in-flight queries serviced by this data service.
|
|
136
|
-
*
|
|
137
|
-
* Used by subclasses that need to abort a concurrent fetch before starting
|
|
138
|
-
* a forced refresh (e.g. `Cache-Control: no-cache` reads), so a slower
|
|
139
|
-
* non-fresh request cannot overwrite the result.
|
|
140
|
-
*
|
|
141
|
-
* @param filters - Optional filter for selecting specific queries.
|
|
142
|
-
* @returns Nothing.
|
|
143
|
-
*/
|
|
144
|
-
protected cancelQueries(filters?: QueryFilters<QueryKey>): Promise<void>;
|
|
145
134
|
/**
|
|
146
135
|
* Initialize the service, rehydrating the cache with persisted data if possible.
|
|
147
136
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseDataService.d.ts","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,gBAAgB,EAChB,eAAe,EACf,gBAAgB,EAChB,eAAe,EAChB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,KAAK,EACV,2BAA2B,EAC3B,8BAA8B,EAC9B,2BAA2B,EAC5B,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAE/C,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EACL,YAAY,EAEZ,eAAe,EACf,iBAAiB,EACjB,YAAY,EACZ,8BAA8B,EAC9B,iBAAiB,EACjB,sBAAsB,EACtB,eAAe,EACf,SAAS,EAET,iBAAiB,EACjB,
|
|
1
|
+
{"version":3,"file":"BaseDataService.d.ts","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,gBAAgB,EAChB,eAAe,EACf,gBAAgB,EAChB,eAAe,EAChB,MAAM,qBAAqB,CAA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C;QAC1B,UAAU,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,CAmCjB;IAED;;;;;;OAMG;IACG,iBAAiB,CACrB,OAAO,CAAC,EAAE,sBAAsB,CAAC,QAAQ,CAAC,EAC1C,OAAO,CAAC,EAAE,iBAAiB,GAC1B,OAAO,CAAC,IAAI,CAAC,CAEf;IAED;;OAEG;IACH,IAAI,IAAI,IAAI,CAKX;IAED;;;OAGG;IACH,OAAO,IAAI,IAAI,CAcd;CAgHF"}
|
package/dist/BaseDataService.js
CHANGED
|
@@ -192,19 +192,6 @@ export class BaseDataService {
|
|
|
192
192
|
async invalidateQueries(filters, options) {
|
|
193
193
|
return this.#queryClient.invalidateQueries(filters, options);
|
|
194
194
|
}
|
|
195
|
-
/**
|
|
196
|
-
* Cancel in-flight queries serviced by this data service.
|
|
197
|
-
*
|
|
198
|
-
* Used by subclasses that need to abort a concurrent fetch before starting
|
|
199
|
-
* a forced refresh (e.g. `Cache-Control: no-cache` reads), so a slower
|
|
200
|
-
* non-fresh request cannot overwrite the result.
|
|
201
|
-
*
|
|
202
|
-
* @param filters - Optional filter for selecting specific queries.
|
|
203
|
-
* @returns Nothing.
|
|
204
|
-
*/
|
|
205
|
-
async cancelQueries(filters) {
|
|
206
|
-
await this.#queryClient.cancelQueries(filters);
|
|
207
|
-
}
|
|
208
195
|
/**
|
|
209
196
|
* Initialize the service, rehydrating the cache with persisted data if possible.
|
|
210
197
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseDataService.js","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAE3D,OAAO,EAWL,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Constraint,\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 QueryFilters,\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-es';\nimport { v4 as uuidV4 } from 'uuid';\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 * between the query client in this data service\n * and the one that `createUIQueryClient` in `@metamask/react-data-query` holds.\n * This global ID will be stored in the `meta` data of the created mutation\n * and included in `:cacheUpdated` payloads. Defaults to a UUID.\n * @returns The mutation results.\n */\n protected async executeMutation<\n TMutationFnData extends Json,\n TDataStruct extends Struct<TMutationFnData> | 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 = uuidV4(),\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 meta: {\n ...options.meta,\n 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 // Type assertion: TypeScript is not able to unify the type that this\n // function returns with `TData` at compile-time. We can still typecheck\n // the arguments, though.\n return processMutationResponse(\n options.mutationKey,\n response,\n responseStruct,\n ) as TData;\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 * Cancel in-flight queries serviced by this data service.\n *\n * Used by subclasses that need to abort a concurrent fetch before starting\n * a forced refresh (e.g. `Cache-Control: no-cache` reads), so a slower\n * non-fresh request cannot overwrite the result.\n *\n * @param filters - Optional filter for selecting specific queries.\n * @returns Nothing.\n */\n protected async cancelQueries(\n filters?: QueryFilters<QueryKey>,\n ): Promise<void> {\n await this.#queryClient.cancelQueries(filters);\n }\n\n /**\n * Initialize the service, rehydrating the cache with persisted data if possible.\n */\n init(): void {\n this.#loadCache().catch(\n /* istanbul ignore next */\n (error) => this.#messenger.captureException?.(error),\n );\n }\n\n /**\n * Prepares the service for garbage collection. This should be extended\n * by any subclasses to clean up any additional connections or events.\n */\n destroy(): void {\n this.#debouncedPersist?.cancel();\n this.#queryCacheUnsubscribe();\n this.#mutationCacheUnsubscribe();\n // `QueryClient.clear()` clears both caches, but `MutationCache.clear()`\n // only drops its references to mutations without clearing their pending\n // garbage-collection timers. We destroy each mutation first so those timers\n // are cleared and do not keep the process alive.\n for (const mutation of this.#queryClient.getMutationCache().getAll()) {\n mutation.destroy();\n }\n this.#queryClient.clear();\n this.messenger.clearSubscriptions();\n this.messenger.clearActions();\n }\n\n /**\n * Publish `cacheUpdated` events when the query or mutation cache is updated.\n *\n * @param objectType - The type of object updated (\"query\" or \"mutation\").\n * @param eventType - What happened to the query or mutation (\"added\" or \"updated\").\n * @param hash - The hash of the query or mutation.\n */\n #publishCacheUpdate(\n objectType: 'query' | 'mutation',\n eventType: CacheUpdatedType,\n hash: string,\n ): void {\n const state =\n eventType === 'added' || eventType === 'updated'\n ? dehydrate(this.#queryClient, {\n shouldDehydrateQuery: (query) =>\n objectType === 'query' && query.queryHash === hash,\n shouldDehydrateMutation: (mutation) =>\n objectType === 'mutation' &&\n mutation.options.mutationKey !== undefined &&\n hashKey(mutation.options.mutationKey) === hash,\n })\n : null;\n\n this.#messenger.publish(\n `${this.name}:cacheUpdated` as const,\n {\n type: eventType,\n objectType,\n hash,\n state,\n } as DataServiceCacheUpdatedPayload,\n );\n this.#messenger.publish(\n `${this.name}:cacheUpdated:${hash}` as const,\n {\n type: eventType,\n objectType,\n state,\n } as DataServiceGranularCacheUpdatedPayload,\n );\n }\n\n /**\n * Persist the query client cache using the StorageService, if the cache is not empty.\n *\n * @returns Nothing.\n */\n async #persistCache(): Promise<void> {\n const state = dehydrate(this.#queryClient, {\n // This is the default, but we specify it to be explicit.\n shouldDehydrateQuery: (query) => query.state.status === 'success',\n });\n\n if (state.queries.length === 0 && state.mutations.length === 0) {\n await this.#externalMessenger.call(\n 'StorageService:removeItem',\n this.name,\n STORAGE_SERVICE_KEY,\n );\n return;\n }\n\n const cache: PersistedCache = {\n timestamp: Date.now(),\n state,\n };\n\n await this.#externalMessenger.call(\n 'StorageService:setItem',\n this.name,\n STORAGE_SERVICE_KEY,\n cache as unknown as Json,\n );\n }\n\n /**\n * Load the query client cache from the StorageService, if persistence is configured\n * and the persisted cache is not expired.\n *\n * @returns Nothing.\n */\n async #loadCache(): Promise<void> {\n if (!this.#persistenceConfig) {\n return;\n }\n\n const { result: untypedCache } = await this.#externalMessenger.call(\n 'StorageService:getItem',\n this.name,\n STORAGE_SERVICE_KEY,\n );\n\n if (!untypedCache) {\n return;\n }\n\n const cache = untypedCache as unknown as PersistedCache;\n\n if (Date.now() - cache.timestamp >= this.#persistenceConfig.maxAge) {\n await this.#externalMessenger.call(\n 'StorageService:removeItem',\n this.name,\n STORAGE_SERVICE_KEY,\n );\n return;\n }\n\n hydrate(this.#queryClient, cache.state);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"BaseDataService.js","sourceRoot":"","sources":["../src/BaseDataService.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAE3D,OAAO,EAWL,WAAW,EAIX,SAAS,EACT,OAAO,EACP,OAAO,GAER,MAAM,sBAAsB,CAAC;AAC9B,OAAO,SAAS,MAAM,iBAAiB,CAAC;AACxC,OAAO,EAAE,QAAQ,EAAiB,MAAM,WAAW,CAAC;AACpD,OAAO,EAAE,EAAE,IAAI,MAAM,EAAE,MAAM,MAAM,CAAC;AAEpC,OAAO,EACL,mBAAmB,GAGpB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AACjE,OAAO,EAAE,uBAAuB,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;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,cAA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wBAAwB,EACxB,IAAI,CAAC,IAAI,EACT,mBAAmB,CACpB,CAAC;QAEF,IAAI,CAAC,YAAY,EAAE,CAAC;YAClB,OAAO;QACT,CAAC;QAED,MAAM,KAAK,GAAG,YAAyC,CAAC;QAExD,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,SAAS,IAAI,IAAI,CAAC,kBAAkB,CAAC,MAAM,EAAE,CAAC;YACnE,MAAM,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAChC,2BAA2B,EAC3B,IAAI,CAAC,IAAI,EACT,mBAAmB,CACpB,CAAC;YACF,OAAO;QACT,CAAC;QAED,OAAO,CAAC,IAAI,CAAC,YAAY,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;IAC1C,CAAC;CACF","sourcesContent":["import {\n Messenger,\n ActionConstraint,\n EventConstraint,\n MessengerActions,\n MessengerEvents,\n} from '@metamask/messenger';\nimport type {\n StorageServiceGetItemAction,\n StorageServiceRemoveItemAction,\n StorageServiceSetItemAction,\n} from '@metamask/storage-service';\nimport { Struct } from '@metamask/superstruct';\nimport { Duration, inMilliseconds } from '@metamask/utils';\nimport type { Json } from '@metamask/utils';\nimport {\n DefaultError,\n DefaultOptions,\n DehydratedState,\n FetchQueryOptions,\n InfiniteData,\n InfiniteQueryPageParamsOptions,\n InvalidateOptions,\n InvalidateQueryFilters,\n 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-es';\nimport { v4 as uuidV4 } from 'uuid';\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 * between the query client in this data service\n * and the one that `createUIQueryClient` in `@metamask/react-data-query` holds.\n * This global ID will be stored in the `meta` data of the created mutation\n * and included in `:cacheUpdated` payloads. Defaults to a UUID.\n * @returns The mutation results.\n */\n protected async executeMutation<\n TMutationFnData extends Json,\n TDataStruct extends Struct<TMutationFnData> | 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 = uuidV4(),\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 meta: {\n ...options.meta,\n 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 // Type assertion: TypeScript is not able to unify the type that this\n // function returns with `TData` at compile-time. We can still typecheck\n // the arguments, though.\n return processMutationResponse(\n options.mutationKey,\n response,\n responseStruct,\n ) as TData;\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"]}
|