Skip to content

Commit a829ba3

Browse files
committed
feat: create a reusable store for objects
1 parent e88c991 commit a829ba3

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

src/packages/core/store/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
export * from './store-base.js';
2+
export * from './store-object-base.js';
23
export * from './store.interface.js';
34
export * from './events/index.js';
45

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
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

Comments
 (0)