UNPKG

@cachex/indexeddb

Version:

IndexedDB implementation of CacheX

95 lines (94 loc) 2.74 kB
// src/index.ts import { AsyncCacheAbsract } from "@cachex/core"; var IndexedDBCache = class extends AsyncCacheAbsract { constructor(db = "cachex") { super(); this.status = "connecting"; this.table = "cache"; const request = window.indexedDB.open(db, 1); request.onerror = () => { this.status = "failed"; console.error(`Database access refused !`); }; request.onupgradeneeded = (ev) => { const db2 = ev.target.result; db2.createObjectStore(this.table); }; request.onsuccess = (ev) => { this.db = ev.target.result; this.status = "ready"; }; } async get(key, defaultValue) { var _a; const data = await this.internalGet(key); if (data && data.expire && data.expire < (/* @__PURE__ */ new Date()).getTime()) { await this.delete(key); return defaultValue; } return (_a = data == null ? void 0 : data.value) != null ? _a : defaultValue; } async set(key, value, ttl) { const data = { value, expire: ttl ? (/* @__PURE__ */ new Date()).getTime() + ttl * 1e3 : void 0 }; const exists = !!await this.internalGet(key); const os = await this.getTransation(); return new Promise((res) => { let query = exists ? os.put(data, key) : os.add(data, key); query.onsuccess = () => res(true); query.onerror = () => res(false); }); } async delete(key) { const os = await this.getTransation(); return new Promise((res) => { const request = os.delete(key); request.onsuccess = () => res(true); request.onerror = () => res(false); }); } async clear() { const os = await this.getTransation(); return new Promise((res) => { const request = os.getAllKeys(); request.onsuccess = async () => { res(await this.deleteMultiple(request.result)); }; }); } async has(key) { return !!await this.get(key); } /** * get the object from the database * @param key the key to get * @returns the object if in the database */ async internalGet(key) { const os = await this.getTransation(); return new Promise((res) => { const query = os.get(key); query.onsuccess = () => res(query.result); query.onerror = () => res(void 0); }); } /** * helper to run a requeset against the database * * @returns the transation ObjectStore */ async getTransation() { while (this.status !== "ready") { if (this.status === "failed") { throw new Error("cannot connect to DB"); } await new Promise((res) => setTimeout(res, 20)); } return this.db.transaction(this.table, "readwrite").objectStore(this.table); } }; export { IndexedDBCache as default };