UNPKG

shelving

Version:

Toolkit for using data in JavaScript.

60 lines (59 loc) 2.53 kB
import { awaitDispose } from "../../util/dispose.js"; import { setMapItem } from "../../util/map.js"; import { getSource } from "../../util/source.js"; import { CacheDBProvider } from "../provider/CacheDBProvider.js"; import { CollectionCache } from "./CollectionCache.js"; /** * Cache of `CollectionCache` objects for multiple collections. * - Use `get(collection)` to retrieve or create the `CollectionCache` for a given collection, * then `getItem(id)` / `getQuery(query)` on that to get a specific store. */ export class DBCache { _collections = new Map(); provider; memory; constructor(provider) { this.provider = provider; // If the provider chain contains a `CacheDBProvider`, reuse its memory so we can seed stores synchronously. this.memory = getSource(CacheDBProvider, provider)?.memory; } _get(collection) { return this._collections.get(collection); } get(collection) { return this._get(collection) || setMapItem(this._collections, collection, new CollectionCache(collection, this.provider, this.memory)); } /** Get (or create) an `ItemStore` for a collection/id in one hop. */ getItem(collection, id) { return this.get(collection).getItem(id); } /** Get (or create) a `QueryStore` for a collection/query in one hop. */ getQuery(collection, query) { return this.get(collection).getQuery(query); } /** Refresh a specific item store for a collection. */ async refreshItem(collection, id, maxAge) { await this._get(collection)?.refreshItem(id, maxAge); } /** Refresh every cached item store for a collection. */ async refreshItems(collection, maxAge) { await this._get(collection)?.refreshItems(maxAge); } /** Refresh a specific query store for a collection. */ async refreshQuery(collection, query, maxAge) { await this._get(collection)?.refreshQuery(query, maxAge); } /** Refresh every cached query store for a collection. */ async refreshQueries(collection, maxAge) { await this._get(collection)?.refreshQueries(maxAge); } /** Refresh every cached store (items and queries) for a collection. */ async refreshAll(collection, maxAge) { await this._get(collection)?.refreshAll(maxAge); } // Implement `AsyncDisposable` async [Symbol.asyncDispose]() { return awaitDispose(...this._collections.values(), // Dispose all collections. () => this._collections.clear()); } }