Skip to content

Instantly share code, notes, and snippets.

@dnkm
Created May 19, 2020 22:18
Show Gist options
  • Save dnkm/dcd7f3f12f099c415d289e9d644aa980 to your computer and use it in GitHub Desktop.
Save dnkm/dcd7f3f12f099c415d289e9d644aa980 to your computer and use it in GitHub Desktop.
indexeddb cache
import Dexie from "dexie";
import { addMinutes } from "date-fns";
import { firestore } from "firebase";
const DB_NAME: string = "id_cache";
const DB_VER: number = 1;
class IdCache {
db: Dexie;
constructor() {
// @ts-ignore
let db = (this.db = new Dexie(DB_NAME));
db.version(DB_VER).stores({
expiry: "id",
students: "id",
groups: "id",
users: "id",
timecards: "id",
});
}
// tries to get, otherwise fetch it and cache
async getOrSet(
storeName: string,
getterFn: () => Promise<any[]>,
{
minutes = 60,
forceRefresh = false,
}: { minutes?: number; forceRefresh?: boolean } = {}
): Promise<any[]> {
let exp = await this.db.table("expiry").get(storeName);
if (
!forceRefresh &&
exp &&
exp.expdate &&
exp.expdate.getTime() >= new Date().getTime()
) {
console.log("✔ cache exists ");
return this.db.table(storeName).toArray();
} else {
console.log("❌ no cache");
let docs = await getterFn();
await this.set(storeName, docs, minutes);
return docs;
}
}
async get(storeName: string): Promise<any[]> {
let exp = await this.db.table("expiry").get(storeName);
if (exp && exp.expdate && exp.expdate.getTime() >= new Date().getTime()) {
console.log("✔ cache exists ");
return this.db.table(storeName).toArray();
} else {
console.log("❌ no cache");
return Promise.resolve([]);
}
}
async set(
storeName: string,
data: any[],
minutes: number = 60
): Promise<any> {
await this.db.table(storeName).clear();
await this.db.table(storeName).bulkAdd(data);
const expdate: Date = addMinutes(new Date(), minutes);
return await this.db.table("expiry").put({ id: storeName, expdate });
}
async updateItem(storeName: string, id: any, data: object): Promise<any> {
return this.db.table(storeName).update(id, data);
}
async deleteItem(storeName: string, id: string): Promise<any> {
return this.db.table(storeName).delete(id);
}
}
const idCache = new IdCache();
export default idCache;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment