shelving
Version:
Toolkit for using data in JavaScript.
59 lines (58 loc) • 1.73 kB
JavaScript
import { withProp } from "../util/object.js";
import { getRequired } from "../util/optional.js";
import { updateData } from "../util/update.js";
import { Store } from "./Store.js";
/** Store a data object. */
export class DataStore extends Store {
/** Get the data of this store. */
get data() {
return this.value;
}
/** Set the data of this store. */
set data(data) {
this.value = data;
}
/** Update several props in this data. */
update(updates) {
this.value = updateData(this.data, updates);
}
/** Update a single named prop in this data. */
getProp(name) {
return this.data[name];
}
/** Update a single named prop in this data. */
setProp(name, value) {
this.value = withProp(this.data, name, value);
}
}
/** Store an optional data object. */
export class OptionalDataStore extends Store {
/** Get current data value of this store (or throw `Promise` that resolves to the next required value). */
get data() {
return getRequired(this.value);
}
/** Set the data of this store. */
set data(data) {
this.value = data;
}
/** Does the data exist or not? */
get exists() {
return !!this.value;
}
/** Update several props in this data. */
update(updates) {
this.value = updateData(this.data, updates);
}
/** Update a single named prop in this data. */
getProp(name) {
return this.data[name];
}
/** Update a single named prop in this data. */
setProp(name, value) {
this.value = withProp(this.data, name, value);
}
/** Set the data to `undefined`. */
unset() {
this.value = undefined;
}
}