From a43f53c38acf13881ec3295dbbbac2e410bbbd34 Mon Sep 17 00:00:00 2001 From: Arthur Ydalgo Date: Fri, 25 Aug 2023 11:37:11 -0300 Subject: [PATCH] Update index.js --- index.js | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/index.js b/index.js index fd03d9e..0dc2629 100644 --- a/index.js +++ b/index.js @@ -63,6 +63,32 @@ module.exports = class CacheStore { return this.put(key, value, ttl); } + async rememberAsync(key, ttl, callback) { + if (this.cacheKeyPrefix) { + key = this.cacheKeyPrefix + key; + } + + let localStorageItem = localStorage.getItem(key); + + let cachedData = localStorageItem + ? JSON.parse(localStorageItem) + : undefined; + + // If cached data exists and doesn't expire, or if cached data expires, but still hasn't + if ( + cachedData && + (!cachedData.expiresAt || + (cachedData.expiresAt && + cachedData.expiresAt > new Date().toISOString())) + ) { + return cachedData.value; + } + + this.put(key, undefined, ttl); + + let value = await callback(); + return this.put(key, value, ttl); + } rememberForever(key, callback) { return this.remember(key, null, callback); }