UNPKG

shelving

Version:

Toolkit for using data in JavaScript.

41 lines (40 loc) 1.44 kB
import { RequiredError } from "../../error/RequiredError.js"; import { countArray, getFirst } from "../../util/array.js"; import { awaitDispose } from "../../util/dispose.js"; /** Provider with a fully asynchronous interface for database access. */ export class DBProvider { async requireItem(collection, id) { const item = await this.getItem(collection, id); if (!item) throw new RequiredError(`Item does not exist in collection "${collection.name}"`, { provider: this, collection, id, caller: this.requireItem, }); return item; } async countQuery(collection, query) { return countArray(await this.getQuery(collection, query)); } async getFirst(collection, query) { return getFirst(await this.getQuery(collection, { ...query, $limit: 1 })); } async requireFirst(collection, query) { const first = await this.getFirst(collection, query); if (!first) throw new RequiredError(`First item does not exist in collection "${collection.name}"`, { provider: this, collection, query, caller: this.requireFirst, }); return first; } // Implement `AsyncDisposable` async [Symbol.asyncDispose]() { await awaitDispose( // Empty by default. ); } }