-
-
Notifications
You must be signed in to change notification settings - Fork 279
Expand file tree
/
Copy pathBaseDataService.ts
More file actions
256 lines (217 loc) · 7.13 KB
/
BaseDataService.ts
File metadata and controls
256 lines (217 loc) · 7.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
import {
Messenger,
ActionConstraint,
EventConstraint,
ActionHandler,
} from '@metamask/messenger';
import type { Json } from '@metamask/utils';
import {
DehydratedState,
FetchInfiniteQueryOptions,
FetchQueryOptions,
InfiniteData,
InvalidateOptions,
InvalidateQueryFilters,
QueryClient,
QueryKey,
WithRequired,
dehydrate,
hashQueryKey,
} from '@tanstack/query-core';
import deepEqual from 'fast-deep-equal';
export type SubscriptionPayload = { hash: string; state: DehydratedState };
export type SubscriptionCallback = (payload: SubscriptionPayload) => void;
export type DataServiceSubscribeAction<ServiceName extends string> = {
type: `${ServiceName}:subscribe`;
handler: (
queryKey: QueryKey,
callback: SubscriptionCallback,
) => DehydratedState;
};
export type DataServiceUnsubscribeAction<ServiceName extends string> = {
type: `${ServiceName}:unsubscribe`;
handler: (queryKey: QueryKey, callback: SubscriptionCallback) => void;
};
export type DataServiceInvalidateQueriesAction<ServiceName extends string> = {
type: `${ServiceName}:invalidateQueries`;
handler: (
filters?: InvalidateQueryFilters<Json>,
options?: InvalidateOptions,
) => Promise<void>;
};
export type DataServiceActions<ServiceName extends string> =
| DataServiceSubscribeAction<ServiceName>
| DataServiceUnsubscribeAction<ServiceName>
| DataServiceInvalidateQueriesAction<ServiceName>;
export type DataServiceCacheUpdateEvent<ServiceName extends string> = {
type: `${ServiceName}:cacheUpdate`;
payload: [SubscriptionPayload];
};
export type DataServiceEvents<ServiceName extends string> =
DataServiceCacheUpdateEvent<ServiceName>;
export class BaseDataService<
ServiceName extends string,
ServiceMessenger extends Messenger<
ServiceName,
ActionConstraint,
EventConstraint,
// Use `any` to allow any parent to be set. `any` is harmless in a type constraint anyway,
// it's the one totally safe place to use it.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
any
>,
> {
public readonly name: ServiceName;
readonly #messenger: Messenger<
ServiceName,
DataServiceActions<ServiceName>,
DataServiceEvents<ServiceName>
>;
readonly #client = new QueryClient();
readonly #subscriptions: Map<string, Set<SubscriptionCallback>> = new Map();
constructor({
name,
messenger,
}: {
name: ServiceName;
messenger: ServiceMessenger;
}) {
this.name = name;
this.#messenger = messenger as unknown as Messenger<
ServiceName,
DataServiceActions<ServiceName>,
DataServiceEvents<ServiceName>
>;
this.#registerMessageHandlers();
this.#setupCacheListener();
}
#registerMessageHandlers(): void {
// Casts are required since `registerActionHandler` isn't able to extract the method parameters correctly.
this.#messenger.registerActionHandler(`${this.name}:subscribe`, ((
queryKey: QueryKey,
callback: SubscriptionCallback,
) => this.#handleSubscribe(queryKey, callback)) as ActionHandler<
DataServiceActions<ServiceName>
>);
this.#messenger.registerActionHandler(`${this.name}:unsubscribe`, ((
queryKey: QueryKey,
callback: SubscriptionCallback,
) => this.#handleUnsubscribe(queryKey, callback)) as ActionHandler<
DataServiceActions<ServiceName>
>);
this.#messenger.registerActionHandler(`${this.name}:invalidateQueries`, ((
filters?: InvalidateQueryFilters<Json>,
options?: InvalidateOptions,
) => this.invalidateQueries(filters, options)) as ActionHandler<
DataServiceActions<ServiceName>
>);
}
#setupCacheListener(): void {
this.#client.getQueryCache().subscribe((event) => {
if (['added', 'updated', 'removed'].includes(event.type)) {
this.#broadcastCacheUpdate(event.query.queryKey);
}
});
}
protected async fetchQuery<
TQueryFnData extends Json,
TError = unknown,
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
>(
options: WithRequired<
FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
'queryKey' | 'queryFn'
>,
): Promise<TData> {
return this.#client.fetchQuery(options);
}
protected async fetchInfiniteQuery<
TQueryFnData extends Json,
TError = unknown,
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
TPageParam extends Json = Json,
>(
options: WithRequired<
FetchInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
'queryKey' | 'queryFn'
>,
pageParam?: TPageParam,
): Promise<TData> {
const query = this.#client
.getQueryCache()
.find<TQueryFnData, TError, TData>({ queryKey: options.queryKey });
if (!query || !pageParam) {
const result = await this.#client.fetchInfiniteQuery({
...options,
queryFn: (context) =>
options.queryFn({
...context,
pageParam: context.pageParam ?? pageParam,
}),
});
return result.pages[0];
}
const { pages } = query.state.data as InfiniteData<TQueryFnData>;
const previous = options.getPreviousPageParam?.(pages[0], pages);
const direction = deepEqual(pageParam, previous) ? 'backward' : 'forward';
const result = (await query.fetch(undefined, {
meta: {
fetchMore: {
direction,
pageParam,
},
},
})) as InfiniteData<TData>;
const pageIndex = result.pageParams.indexOf(pageParam);
return result.pages[pageIndex];
}
async invalidateQueries<TPageData extends Json>(
filters?: InvalidateQueryFilters<TPageData>,
options?: InvalidateOptions,
): Promise<void> {
return this.#client.invalidateQueries(filters, options);
}
#handleSubscribe(
queryKey: QueryKey,
subscription: SubscriptionCallback,
): DehydratedState {
const hash = hashQueryKey(queryKey);
if (!this.#subscriptions.has(hash)) {
this.#subscriptions.set(hash, new Set());
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
this.#subscriptions.get(hash)!.add(subscription);
return this.#getDehydratedState(queryKey);
}
#handleUnsubscribe(
queryKey: QueryKey,
subscription: SubscriptionCallback,
): void {
const hash = hashQueryKey(queryKey);
const subscribers = this.#subscriptions.get(hash);
subscribers?.delete(subscription);
if (subscribers?.size === 0) {
this.#subscriptions.delete(hash);
}
}
#getDehydratedState(queryKey: QueryKey): DehydratedState {
const hash = hashQueryKey(queryKey);
return dehydrate(this.#client, {
shouldDehydrateQuery: (query) => query.queryHash === hash,
});
}
#broadcastCacheUpdate(queryKey: QueryKey): void {
const hash = hashQueryKey(queryKey);
const state = this.#getDehydratedState(queryKey);
const payload = {
hash,
state,
};
this.#messenger.publish(`${this.name}:cacheUpdate` as const, payload);
// TODO: Determine if we can leverage `messenger.publish` entirely in order to not keep track of subscriptions manually.
const subscribers = this.#subscriptions.get(hash);
subscribers?.forEach((subscriber) => subscriber(payload));
}
}