Skip to content

Commit fe1fd2d

Browse files
committed
fix: add cache header for cachedFetch
1 parent ef9f8c1 commit fe1fd2d

1 file changed

Lines changed: 19 additions & 5 deletions

File tree

app/composables/useCachedFetch.ts

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import type { CachedFetchResult } from '#shared/utils/fetch-cache-config'
1+
import { type CachedFetchResult, FETCH_CACHE_DEFAULT_TTL } from '#shared/utils/fetch-cache-config'
2+
import defu from 'defu'
23

34
/**
45
* Get the cachedFetch function from the current request context.
@@ -30,13 +31,20 @@ import type { CachedFetchResult } from '#shared/utils/fetch-cache-config'
3031
*/
3132
export function useCachedFetch(): CachedFetchFunction {
3233
// On client, return a function that just uses $fetch (no caching, not stale)
34+
3335
if (import.meta.client) {
3436
return async <T = unknown>(
3537
url: string,
3638
options: Parameters<typeof $fetch>[1] = {},
37-
_ttl?: number,
39+
ttl: number = FETCH_CACHE_DEFAULT_TTL,
3840
): Promise<CachedFetchResult<T>> => {
39-
const data = (await $fetch<T>(url, options)) as T
41+
const defaultFetchOptions: Parameters<typeof $fetch>[1] = {
42+
headers: {
43+
'Cache-Control': `max-age=${ttl}, must-revalidate`,
44+
},
45+
}
46+
47+
const data = (await $fetch<T>(url, defu(options, defaultFetchOptions))) as T
4048
return { data, isStale: false, cachedAt: null }
4149
}
4250
}
@@ -55,9 +63,15 @@ export function useCachedFetch(): CachedFetchFunction {
5563
return async <T = unknown>(
5664
url: string,
5765
options: Parameters<typeof $fetch>[1] = {},
58-
_ttl?: number,
66+
ttl: number = FETCH_CACHE_DEFAULT_TTL,
5967
): Promise<CachedFetchResult<T>> => {
60-
const data = (await $fetch<T>(url, options)) as T
68+
const defaultFetchOptions: Parameters<typeof $fetch>[1] = {
69+
headers: {
70+
'Cache-Control': `max-age=${ttl}, must-revalidate`,
71+
},
72+
}
73+
74+
const data = (await $fetch<T>(url, defu(options, defaultFetchOptions))) as T
6175
return { data, isStale: false, cachedAt: null }
6276
}
6377
}

0 commit comments

Comments
 (0)