Last active
December 12, 2021 05:38
-
-
Save cameronapak/e6eb84a6e6162585ec5e5136a768f61f to your computer and use it in GitHub Desktop.
A simiple way to cache an API call using localStorage.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Locale Storage API caching solution. | |
// Idea from dagalti from Stack Overflow. See https://stackoverflow.com/a/64095328/6598861. | |
const internalKey = 'local-storage-caching' | |
/** | |
* Set API call in cache: a localStorage caching solution. | |
* | |
* @param {object} params - The function params. | |
* @param {number} [params.cacheLifetime] - Duration in seconds of the cache. | |
* @param {string} params.key - A unique key to get and request data from localStorage. | |
* @param {object} params.data - The data to be saved in cache. | |
*/ | |
export function setApiInCache({ | |
cacheLifetime, | |
key, | |
data | |
}) { | |
if (!data || !key) { | |
throw new Error('setApiInCache: `data` or `key` param does not exist.') | |
} | |
if (!localStorage) { | |
throw new Error('setApiInCache: `localStorage` does not exist.') | |
} | |
const lifetime = cacheLifetime || 14400 // Defaults to 4 hours. | |
const startDate = parseInt(Date.now() / 1000) | |
const endDate = startDate + lifetime | |
const json = { | |
data, | |
endDate, | |
startDate, | |
} | |
localStorage.setItem(`${internalKey}-${key}`, JSON.stringify(json)) | |
} | |
/** | |
* Gets the API call from cache: a localStorage caching solution. | |
* | |
* @param {object} params - The function params. | |
* @param {string} params.key - A unique key to get and request data from localStorage. | |
* | |
* @returns {boolean|object} - Returns the data if it exists. Otherwise it returns false. | |
*/ | |
export function getApiFromCache({ | |
key, | |
}) { | |
if (!key) { | |
throw new Error('getApiFromCache: `key` param does not exist.') | |
} | |
if (!localStorage) { | |
throw new Error('setApiInCache: `localStorage` does not exist.') | |
} | |
let localStorageData = {} | |
try { | |
const parsedData = JSON.parse(localStorage.getItem(`${internalKey}-${key}`)) | |
if (parsedData) { | |
localStorageData = parsedData | |
} | |
} catch { | |
return false | |
} | |
const { | |
data, | |
endDate, | |
startDate, | |
} = localStorageData | |
if (data && startDate && endDate) { | |
const expired = Boolean((parseInt(Date.now() / 1000) - endDate) > 1) | |
if (!expired) { | |
return data | |
} else { | |
localStorage.removeItem(`${internalKey}-${key}`) | |
} | |
} | |
return false | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment