Example:
import { resourceCache } from './resourceCache'
// Given a resource resolver, create one that auto caches
const getAuth = resourceCache(async () => {
// Fetch the resource
const token = await fetchApiToken()
// Expire it after 5 minutes
const exp = Date.now() + (5 * 60 * 1000)
return { token, exp }
})
export async function fetchMyApi(path, options, retryOn401 = true) {
const auth = await getAuth()
const response = await fetch(baseURL + path, {
...options,
headers: {
Authorization: `Bearer ${auth.token}`,
...options?.headers,
}
})
if (retryOn401 && response.status === 401) {
// Invalidate used `auth` and retry.
auth.exp = 0
return fetchMyApi(path, options, false)
}
if (!response.ok) { ... }
return response.json()
}