shelving
Version:
Toolkit for using data in JavaScript.
66 lines (65 loc) • 2.28 kB
JavaScript
import { RequiredError } from "../error/RequiredError.js";
import { countArray } from "../util/array.js";
import { getFirst } from "../util/array.js";
/** Provider with a fully synchronous interface */
export class Provider {
requireItem(collection, id) {
const item = this.getItem(collection, id);
if (!item)
throw new RequiredError(`Item does not exist in collection "${collection}"`, {
provider: this,
collection,
id,
caller: this.getItem,
});
return item;
}
countQuery(collection, query) {
return countArray(this.getQuery(collection, query));
}
getFirst(collection, query) {
return getFirst(this.getQuery(collection, { ...query, $limit: 1 }));
}
requireFirst(collection, query) {
const first = this.getFirst(collection, query);
if (!first)
throw new RequiredError(`First item does not exist in collection "${collection}"`, {
provider: this,
collection,
query,
caller: this.requireFirst,
});
return first;
}
}
/** Provider with a fully asynchronous interface */
export class AsyncProvider {
async requireItem(collection, id) {
const item = await this.getItem(collection, id);
if (!item)
throw new RequiredError(`Item does not exist in collection "${collection}"`, {
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}"`, {
provider: this,
collection,
query,
caller: this.requireFirst,
});
return first;
}
}