UNPKG

shelving

Version:

Toolkit for using data in JavaScript.

69 lines (68 loc) 2.79 kB
import { awaitDispose } from "../../util/dispose.js"; import { DBProvider } from "./DBProvider.js"; import { MemoryDBProvider } from "./MemoryDBProvider.js"; /** Keep a copy of asynchronous remote data in a local synchronous cache. */ export class CacheDBProvider extends DBProvider { source; memory; constructor(source, cache = new MemoryDBProvider()) { super(); this.source = source; this.memory = cache; } async getItem(collection, id) { const item = await this.source.getItem(collection, id); const table = this.memory.getTable(collection); item ? table.setItem(id, item) : table.deleteItem(id); return item; } getItemSequence(collection, id) { return this.memory.getTable(collection).setItemSequence(id, this.source.getItemSequence(collection, id)); } async addItem(collection, data) { const id = await this.source.addItem(collection, data); this.memory.getTable(collection).setItem(id, data); return id; } async setItem(collection, id, data) { await this.source.setItem(collection, id, data); this.memory.getTable(collection).setItem(id, data); } async updateItem(collection, id, updates) { await this.source.updateItem(collection, id, updates); this.memory.getTable(collection).updateItem(id, updates); } async deleteItem(collection, id) { await this.source.deleteItem(collection, id); this.memory.getTable(collection).deleteItem(id); } countQuery(collection, query) { return this.source.countQuery(collection, query); } async getQuery(collection, query) { const items = await this.source.getQuery(collection, query); this.memory.getTable(collection).setItems(items); return items; } getQuerySequence(collection, query) { return this.memory.getTable(collection).setItemsSequence(this.source.getQuerySequence(collection, query)); } async setQuery(collection, query, data) { await this.source.setQuery(collection, query, data); this.memory.getTable(collection).setQuery(query, data); } async updateQuery(collection, query, updates) { await this.source.updateQuery(collection, query, updates); this.memory.getTable(collection).updateQuery(query, updates); } async deleteQuery(collection, query) { await this.source.deleteQuery(collection, query); this.memory.getTable(collection).deleteQuery(query); } // Implement `AsyncDisposable` async [Symbol.asyncDispose]() { await awaitDispose(this.source, // Dispose the source API provider. this.memory, // Dispose the source API provider. super[Symbol.asyncDispose]()); } }