Created
October 11, 2022 20:40
-
-
Save bdadam/f366a146fce0a6eff4f4e18d1db6d3bf to your computer and use it in GitHub Desktop.
SWR Cache
This file contains 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
// createCache.ts | |
export default function createCache(fetchFunction: () => Promise<any>, refreshInterval: number, retryAfter: number) { | |
let fetchPromise: null | ReturnType<typeof fetchFunction> = null; | |
const doThinInInterval = () => { | |
fetchFunction().then((data) => { | |
fetchPromise = Promise.resolve(data); | |
}) | |
.catch(() => setTimeout(doThinInInterval, retryAfter)); | |
} | |
setInterval(doThinInInterval, refreshInterval); | |
return () => { | |
if (!fetchPromise) { | |
fetchPromise = fetchFunction(); | |
} | |
return fetchPromise; | |
} | |
} | |
// identity-token.ts | |
//import createCache from './createCache'; | |
async function fetchSsmSecretAndIdentityToken(timeout: number): Promise<string> { | |
const timeoutPromise = new Promise((resolve, reject) => setTimeout(reject, timeout)); | |
try { | |
const x = Promise.race(['abcdef', timeoutPromise]); | |
return x; | |
} | |
catch(e) { | |
throw new Error('') | |
} | |
} | |
const cache = createCache(fetchSsmSecretAndIdentityToken, 10_000_000, 5_000) | |
const x = await cache(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment