1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | import {EventEmitter} from 'events';
|
7 | import debugFactory from 'debug';
|
8 | import {Binding} from './binding';
|
9 | import {BindingFilter} from './binding-filter';
|
10 | import {BindingComparator} from './binding-sorter';
|
11 | import {Context} from './context';
|
12 | import {ContextEvent} from './context-event';
|
13 | import {ContextEventType, ContextObserver} from './context-observer';
|
14 | import {Subscription} from './context-subscription';
|
15 | import {Getter} from './inject';
|
16 | import {
|
17 | asResolutionOptions,
|
18 | ResolutionOptions,
|
19 | ResolutionOptionsOrSession,
|
20 | ResolutionSession,
|
21 | } from './resolution-session';
|
22 | import {isPromiseLike, resolveList, ValueOrPromise} from './value-promise';
|
23 |
|
24 | const debug = debugFactory('loopback:context:view');
|
25 |
|
26 |
|
27 |
|
28 |
|
29 | export interface ContextViewEvent<T> extends ContextEvent {
|
30 | |
31 |
|
32 |
|
33 | cachedValue?: T;
|
34 | }
|
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 |
|
45 |
|
46 |
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 | export class ContextView<T = unknown>
|
53 | extends EventEmitter
|
54 | implements ContextObserver
|
55 | {
|
56 | |
57 |
|
58 |
|
59 | protected _cachedBindings: Readonly<Binding<T>>[] | undefined;
|
60 | |
61 |
|
62 |
|
63 | protected _cachedValues: Map<Readonly<Binding<T>>, T> | undefined;
|
64 | private _subscription: Subscription | undefined;
|
65 |
|
66 | |
67 |
|
68 |
|
69 |
|
70 |
|
71 |
|
72 | constructor(
|
73 | public readonly context: Context,
|
74 | public readonly filter: BindingFilter,
|
75 | public readonly comparator?: BindingComparator,
|
76 | private resolutionOptions?: Omit<ResolutionOptions, 'session'>,
|
77 | ) {
|
78 | super();
|
79 | }
|
80 |
|
81 | |
82 |
|
83 |
|
84 |
|
85 | private updateCachedValues(values: T[]) {
|
86 | if (this._cachedBindings == null) return undefined;
|
87 | this._cachedValues = new Map();
|
88 | for (let i = 0; i < this._cachedBindings?.length; i++) {
|
89 | this._cachedValues.set(this._cachedBindings[i], values[i]);
|
90 | }
|
91 | return this._cachedValues;
|
92 | }
|
93 |
|
94 | |
95 |
|
96 |
|
97 | private getCachedValues() {
|
98 | return Array.from(this._cachedValues?.values() ?? []);
|
99 | }
|
100 |
|
101 | |
102 |
|
103 |
|
104 | open() {
|
105 | debug('Start listening on changes of context %s', this.context.name);
|
106 | if (this.context.isSubscribed(this)) {
|
107 | return this._subscription;
|
108 | }
|
109 | this._subscription = this.context.subscribe(this);
|
110 | return this._subscription;
|
111 | }
|
112 |
|
113 | |
114 |
|
115 |
|
116 | close() {
|
117 | debug('Stop listening on changes of context %s', this.context.name);
|
118 | if (!this._subscription || this._subscription.closed) return;
|
119 | this._subscription.unsubscribe();
|
120 | this._subscription = undefined;
|
121 | this.emit('close');
|
122 | }
|
123 |
|
124 | |
125 |
|
126 |
|
127 |
|
128 | get bindings(): Readonly<Binding<T>>[] {
|
129 | debug('Reading bindings');
|
130 | if (this._cachedBindings == null) {
|
131 | this._cachedBindings = this.findBindings();
|
132 | }
|
133 | return this._cachedBindings;
|
134 | }
|
135 |
|
136 | |
137 |
|
138 |
|
139 | protected findBindings(): Readonly<Binding<T>>[] {
|
140 | debug('Finding matching bindings');
|
141 | const found = this.context.find(this.filter);
|
142 | if (typeof this.comparator === 'function') {
|
143 | found.sort(this.comparator);
|
144 | }
|
145 |
|
146 | if (debug.enabled) {
|
147 | debug(
|
148 | 'Bindings found',
|
149 | found.map(b => b.key),
|
150 | );
|
151 | }
|
152 | return found;
|
153 | }
|
154 |
|
155 | |
156 |
|
157 |
|
158 | observe(
|
159 | event: ContextEventType,
|
160 | binding: Readonly<Binding<unknown>>,
|
161 | context: Context,
|
162 | ) {
|
163 | const ctxEvent: ContextViewEvent<T> = {
|
164 | context,
|
165 | binding,
|
166 | type: event,
|
167 | };
|
168 | debug('Observed event %s %s %s', event, binding.key, context.name);
|
169 |
|
170 | if (event === 'unbind') {
|
171 | const cachedValue = this._cachedValues?.get(
|
172 | binding as Readonly<Binding<T>>,
|
173 | );
|
174 | this.emit(event, {...ctxEvent, cachedValue});
|
175 | } else {
|
176 | this.emit(event, ctxEvent);
|
177 | }
|
178 |
|
179 | this.refresh();
|
180 | }
|
181 |
|
182 | |
183 |
|
184 |
|
185 | refresh() {
|
186 | debug('Refreshing the view by invalidating cache');
|
187 | this._cachedBindings = undefined;
|
188 | this._cachedValues = undefined;
|
189 | this.emit('refresh');
|
190 | }
|
191 |
|
192 | |
193 |
|
194 |
|
195 |
|
196 | resolve(session?: ResolutionOptionsOrSession): ValueOrPromise<T[]> {
|
197 | debug('Resolving values');
|
198 | if (this._cachedValues != null) {
|
199 | return this.getCachedValues();
|
200 | }
|
201 | const bindings = this.bindings;
|
202 | let result = resolveList(bindings, b => {
|
203 | const options = {
|
204 | ...this.resolutionOptions,
|
205 | ...asResolutionOptions(session),
|
206 | };
|
207 |
|
208 |
|
209 |
|
210 | options.session = undefined;
|
211 | return b.getValue(this.context, options);
|
212 | });
|
213 | if (isPromiseLike(result)) {
|
214 | result = result.then(values => {
|
215 | const list = values.filter(v => v != null) as T[];
|
216 | this.updateCachedValues(list);
|
217 | this.emit('resolve', list);
|
218 | return list;
|
219 | });
|
220 | } else {
|
221 |
|
222 | const list = (result = result.filter(v => v != null) as T[]);
|
223 | this.updateCachedValues(list);
|
224 | this.emit('resolve', list);
|
225 | }
|
226 | return result as ValueOrPromise<T[]>;
|
227 | }
|
228 |
|
229 | |
230 |
|
231 |
|
232 |
|
233 | async values(session?: ResolutionOptionsOrSession): Promise<T[]> {
|
234 | debug('Reading values');
|
235 |
|
236 | await new Promise<void>(resolve => {
|
237 | process.nextTick(() => resolve());
|
238 | });
|
239 | if (this._cachedValues == null) {
|
240 | return this.resolve(session);
|
241 | }
|
242 | return this.getCachedValues();
|
243 | }
|
244 |
|
245 | |
246 |
|
247 |
|
248 | asGetter(session?: ResolutionOptionsOrSession): Getter<T[]> {
|
249 | return () => this.values(session);
|
250 | }
|
251 |
|
252 | |
253 |
|
254 |
|
255 | async singleValue(
|
256 | session?: ResolutionOptionsOrSession,
|
257 | ): Promise<T | undefined> {
|
258 | const values = await this.values(session);
|
259 | if (values.length === 0) return undefined;
|
260 | if (values.length === 1) return values[0];
|
261 | throw new Error(
|
262 | 'The ContextView has more than one value. Use values() to access them.',
|
263 | );
|
264 | }
|
265 |
|
266 | |
267 |
|
268 |
|
269 |
|
270 |
|
271 |
|
272 | on(
|
273 | eventName: 'bind',
|
274 | listener: <V>(event: ContextViewEvent<V>) => void,
|
275 | ): this;
|
276 |
|
277 | |
278 |
|
279 |
|
280 |
|
281 |
|
282 |
|
283 | on(
|
284 | eventName: 'unbind',
|
285 | listener: <V>(event: ContextViewEvent<V> & {cachedValue?: V}) => void,
|
286 | ): this;
|
287 |
|
288 | |
289 |
|
290 |
|
291 |
|
292 |
|
293 |
|
294 |
|
295 | on(eventName: 'refresh', listener: () => void): this;
|
296 |
|
297 | |
298 |
|
299 |
|
300 |
|
301 |
|
302 |
|
303 |
|
304 |
|
305 | on(eventName: 'refresh', listener: <V>(result: V[]) => void): this;
|
306 |
|
307 | |
308 |
|
309 |
|
310 |
|
311 |
|
312 |
|
313 |
|
314 |
|
315 | on(eventName: 'close', listener: () => void): this;
|
316 |
|
317 |
|
318 |
|
319 | on(event: string | symbol, listener: (...args: any[]) => void): this;
|
320 |
|
321 |
|
322 | on(event: string | symbol, listener: (...args: any[]) => void): this {
|
323 | return super.on(event, listener);
|
324 | }
|
325 |
|
326 | |
327 |
|
328 |
|
329 |
|
330 |
|
331 |
|
332 | once(
|
333 | eventName: 'bind',
|
334 | listener: <V>(event: ContextViewEvent<V>) => void,
|
335 | ): this;
|
336 |
|
337 | |
338 |
|
339 |
|
340 |
|
341 |
|
342 |
|
343 | once(
|
344 | eventName: 'unbind',
|
345 | listener: <V>(event: ContextViewEvent<V> & {cachedValue?: V}) => void,
|
346 | ): this;
|
347 |
|
348 | |
349 |
|
350 |
|
351 |
|
352 |
|
353 |
|
354 |
|
355 | once(eventName: 'refresh', listener: () => void): this;
|
356 |
|
357 | |
358 |
|
359 |
|
360 |
|
361 |
|
362 |
|
363 |
|
364 |
|
365 | once(eventName: 'refresh', listener: <V>(result: V[]) => void): this;
|
366 |
|
367 | |
368 |
|
369 |
|
370 |
|
371 |
|
372 |
|
373 |
|
374 |
|
375 | once(eventName: 'close', listener: () => void): this;
|
376 |
|
377 |
|
378 |
|
379 | once(event: string | symbol, listener: (...args: any[]) => void): this;
|
380 |
|
381 |
|
382 | once(event: string | symbol, listener: (...args: any[]) => void): this {
|
383 | return super.once(event, listener);
|
384 | }
|
385 | }
|
386 |
|
387 |
|
388 |
|
389 |
|
390 |
|
391 |
|
392 |
|
393 | export function createViewGetter<T = unknown>(
|
394 | ctx: Context,
|
395 | bindingFilter: BindingFilter,
|
396 | session?: ResolutionSession,
|
397 | ): Getter<T[]>;
|
398 |
|
399 |
|
400 |
|
401 |
|
402 |
|
403 |
|
404 |
|
405 |
|
406 |
|
407 | export function createViewGetter<T = unknown>(
|
408 | ctx: Context,
|
409 | bindingFilter: BindingFilter,
|
410 | bindingComparator?: BindingComparator,
|
411 | session?: ResolutionOptionsOrSession,
|
412 | ): Getter<T[]>;
|
413 |
|
414 |
|
415 |
|
416 |
|
417 |
|
418 |
|
419 |
|
420 |
|
421 |
|
422 | export function createViewGetter<T = unknown>(
|
423 | ctx: Context,
|
424 | bindingFilter: BindingFilter,
|
425 | bindingComparatorOrSession?: BindingComparator | ResolutionSession,
|
426 | session?: ResolutionOptionsOrSession,
|
427 | ): Getter<T[]> {
|
428 | let bindingComparator: BindingComparator | undefined = undefined;
|
429 | if (typeof bindingComparatorOrSession === 'function') {
|
430 | bindingComparator = bindingComparatorOrSession;
|
431 | } else if (bindingComparatorOrSession instanceof ResolutionSession) {
|
432 | session = bindingComparatorOrSession;
|
433 | }
|
434 |
|
435 | const options = asResolutionOptions(session);
|
436 | const view = new ContextView<T>(
|
437 | ctx,
|
438 | bindingFilter,
|
439 | bindingComparator,
|
440 | options,
|
441 | );
|
442 | view.open();
|
443 | return view.asGetter(options);
|
444 | }
|