Skip to content

Instantly share code, notes, and snippets.

@bdadam
Created October 11, 2022 20:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bdadam/f366a146fce0a6eff4f4e18d1db6d3bf to your computer and use it in GitHub Desktop.
Save bdadam/f366a146fce0a6eff4f4e18d1db6d3bf to your computer and use it in GitHub Desktop.
SWR Cache
// 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