Skip to content

Commit

Permalink
Add conditional fetch caching with revalidation option
Browse files Browse the repository at this point in the history
  • Loading branch information
jrhoads committed Jan 20, 2025
1 parent c22c6f3 commit 3f9bc2b
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/data/queries/doiQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import apolloClient from 'src/utils/apolloClient/apolloClient'
import { WorkMetadata, Work } from 'src/data/types'
import { workFragment } from 'src/data/queries/queryFragments'
import { mapJsonToWork } from 'src/utils/helpers'
import fetchConditionalCache from 'src/utils/fetchConditionalCache'

function buildDoiSearchParams(id: string): URLSearchParams {
return new URLSearchParams({
Expand Down Expand Up @@ -30,7 +31,7 @@ export async function fetchDoi(id: string) {
}
const searchParams = buildDoiSearchParams(id)

const res = await fetch(
const res = await fetchConditionalCache(
`${process.env.NEXT_PUBLIC_API_URL}/dois?${searchParams.toString()}`,
options
)
Expand Down
29 changes: 29 additions & 0 deletions src/utils/fetchConditionalCache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
const ONE_HOUR = 60 * 60;
interface FetchConditionalCacheOptions extends RequestInit {
revalidate?: number;
}

async function fetchConditionalCache(
url: string,
options?: FetchConditionalCacheOptions
) {
// Destructure revalidate, spread the rest into fetchOptions
const { revalidate, ...fetchOptions } = options || {};
const isCacheEnabled = revalidate !== undefined;
const nextOptions = isCacheEnabled ? { revalidate: revalidate } : { revalidate: ONE_HOUR };

const response = await fetch(url, {
cache: 'no-store',
...fetchOptions
});

if (response.ok) {
return fetch(url, {
...fetchOptions,
next: nextOptions
});
}

return response;
}
export default fetchConditionalCache

0 comments on commit 3f9bc2b

Please sign in to comment.