shelving
Version:
Toolkit for using data in JavaScript.
67 lines (66 loc) • 2.09 kB
JavaScript
import { RequiredError } from "../error/RequiredError.js";
import { getGetter } from "../util/class.js";
import { withProp } from "../util/object.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. */
get(name) {
return this.data[name];
}
/** Update a single named prop in this data. */
set(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 this.require(getGetter(this, "data"));
}
/** Set the data of this store. */
set data(data) {
this.value = data;
}
/** Does the data exist or not? */
get exists() {
return !!this.value;
}
/** Require the data for this data store, or throw `RequiredError` if it is not set. */
require(caller = this.require) {
const data = this.value;
if (!data)
throw new RequiredError("Data is empty", { caller });
return data;
}
/** Update several props in this data. */
update(updates) {
this.value = updateData(this.require(this.update), updates);
}
/** Update a single named prop in this data. */
get(name) {
return this.require(this.get)[name];
}
/** Update a single named prop in this data. */
set(name, value) {
this.value = withProp(this.require(this.set), name, value);
}
/** Set the data to `undefined`. */
delete() {
this.value = undefined;
}
}