UNPKG

shelving

Version:

Toolkit for using data in JavaScript.

45 lines (44 loc) 1.67 kB
import { RequiredError } from "../../error/RequiredError.js"; import { FetchStore } from "../../store/FetchStore.js"; import { getGetter } from "../../util/class.js"; import { NONE } from "../../util/constants.js"; import { getItem } from "../../util/item.js"; import { runSequence } from "../../util/sequence.js"; /** Store that stores a single item in a collection from a database provider. */ export class ItemStore extends FetchStore { provider; collection; id; /** * The required item data of this store. * @throws {RequiredError} if item doesn't exist (i.e. if `this.value` is `undefined` */ get item() { const item = this.value; if (!item) throw new RequiredError(`Item does not exist in collection "${this.collection.name}"`, { store: this, provider: this.provider, collection: this.collection.name, id: this.id, caller: getGetter(this, "item"), }); return item; } set item(data) { this.value = getItem(this.id, data); } constructor(collection, id, provider, memory) { const item = memory?.getTable(collection).getItem(id); super(item ?? NONE); // Use the current memory snapshot if available. if (memory) this.starter = store => runSequence(store.through(memory.getItemSequence(collection, id))); this.provider = provider; this.collection = collection; this.id = id; } // Override to get the item from the provider. _fetch(_signal) { return this.provider.getItem(this.collection, this.id); } }