@graphql-mesh/cache-localforage
Version:
38 lines (37 loc) • 1.59 kB
JavaScript
import LocalForage from 'localforage';
import { createInMemoryLRUDriver } from './InMemoryLRUDriver.js';
LocalForage.defineDriver(createInMemoryLRUDriver()).catch(err => console.error('Failed at defining InMemoryLRU driver', err));
export default class LocalforageCache {
constructor(config) {
const driverNames = config?.driver || ['INDEXEDDB', 'WEBSQL', 'LOCALSTORAGE', 'INMEMORY_LRU'];
this.localforage = LocalForage.createInstance({
name: config?.name || 'graphql-mesh-cache',
storeName: config?.storeName || 'graphql-mesh-cache-store',
driver: driverNames.map(driverName => LocalForage[driverName] ?? driverName),
size: config?.size,
version: config?.version,
description: config?.description,
});
}
async get(key) {
const expiresAt = await this.localforage.getItem(`${key}.expiresAt`);
if (expiresAt && Date.now() > expiresAt) {
await this.localforage.removeItem(key);
}
return this.localforage.getItem(key.toString());
}
async getKeysByPrefix(prefix) {
const keys = await this.localforage.keys();
return keys.filter(key => key.startsWith(prefix));
}
async set(key, value, options) {
const jobs = [this.localforage.setItem(key, value)];
if (options?.ttl) {
jobs.push(this.localforage.setItem(`${key}.expiresAt`, Date.now() + options.ttl * 1000));
}
await Promise.all(jobs);
}
delete(key) {
return this.localforage.removeItem(key);
}
}