|
| 1 | +import { UmbStoreUpdateEvent } from './events/index.js'; |
| 2 | +import { UmbContextBase } from '@umbraco-cms/backoffice/class-api'; |
| 3 | +import { type Observable, UmbObjectState } from '@umbraco-cms/backoffice/observable-api'; |
| 4 | +import type { UmbControllerHost } from '@umbraco-cms/backoffice/controller-api'; |
| 5 | +import type { UmbApi } from '@umbraco-cms/backoffice/extension-api'; |
| 6 | + |
| 7 | +/** |
| 8 | + * The base class for a store that holds an object. |
| 9 | + */ |
| 10 | +export class UmbStoreObjectBase<T> extends UmbContextBase<never> implements UmbApi { |
| 11 | + protected _data: UmbObjectState<T>; |
| 12 | + |
| 13 | + constructor(host: UmbControllerHost, storeAlias: string, initialData?: T) { |
| 14 | + super(host, storeAlias); |
| 15 | + this._data = new UmbObjectState(initialData ?? ({} as T)); |
| 16 | + } |
| 17 | + |
| 18 | + /** |
| 19 | + * Updates the store with the given data |
| 20 | + * @param data - The (partial) data to update the store with |
| 21 | + * @memberof UmbStoreObjectBase |
| 22 | + */ |
| 23 | + update(data: Partial<T>) { |
| 24 | + this._data.update(data); |
| 25 | + this.dispatchEvent(new UmbStoreUpdateEvent([])); |
| 26 | + } |
| 27 | + |
| 28 | + /** |
| 29 | + * Returns the current state of the store |
| 30 | + * @memberof UmbStoreObjectBase |
| 31 | + */ |
| 32 | + getState(): T { |
| 33 | + return this._data.getValue(); |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * Returns an observable of the store |
| 38 | + * @memberof UmbStoreObjectBase |
| 39 | + */ |
| 40 | + all() { |
| 41 | + return this._data.asObservable(); |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * Returns an observable of a part of the store |
| 46 | + * @param key - The key of the part to return |
| 47 | + * @memberof UmbStoreObjectBase |
| 48 | + */ |
| 49 | + part<Part extends keyof T>(key: Part): Observable<T[Part]> { |
| 50 | + return this._data.asObservablePart((data) => data[key]); |
| 51 | + } |
| 52 | + |
| 53 | + /** |
| 54 | + * Destroys the store |
| 55 | + * @memberof UmbStoreObjectBase |
| 56 | + */ |
| 57 | + override destroy() { |
| 58 | + this._data.destroy(); |
| 59 | + } |
| 60 | +} |
0 commit comments