( req: Request, ttl: number | undefined, globalCacheSettings: boolean, personalized: boolean, )
| 11 | * @param personalized Whether requests depend on the authentication status of users |
| 12 | */ |
| 13 | export function getCacheControlHeader( |
| 14 | req: Request, |
| 15 | ttl: number | undefined, |
| 16 | globalCacheSettings: boolean, |
| 17 | personalized: boolean, |
| 18 | ): string { |
| 19 | const env = useEnv(); |
| 20 | |
| 21 | // When the user explicitly asked to skip the cache |
| 22 | if (shouldSkipCache(req)) return 'no-store'; |
| 23 | |
| 24 | // When the resource / current request shouldn't be cached |
| 25 | if (ttl === undefined || ttl < 0) return 'no-cache'; |
| 26 | |
| 27 | // When the API cache can invalidate at any moment |
| 28 | if (globalCacheSettings && env['CACHE_AUTO_PURGE'] === true) return 'no-cache'; |
| 29 | |
| 30 | const headerValues = []; |
| 31 | |
| 32 | // When caching depends on the authentication status of the users |
| 33 | if (personalized) { |
| 34 | // Allow response to be stored in shared cache (public) or local cache only (private) |
| 35 | const access = !!req.accountability?.role === false ? 'public' : 'private'; |
| 36 | headerValues.push(access); |
| 37 | } |
| 38 | |
| 39 | // Cache control header uses seconds for everything |
| 40 | const ttlSeconds = Math.round(ttl / 1000); |
| 41 | headerValues.push(`max-age=${ttlSeconds}`); |
| 42 | |
| 43 | // When the s-maxage flag should be included |
| 44 | if ( |
| 45 | globalCacheSettings && |
| 46 | Number.isInteger(env['CACHE_CONTROL_S_MAXAGE']) && |
| 47 | (env['CACHE_CONTROL_S_MAXAGE'] as number) >= 0 |
| 48 | ) { |
| 49 | headerValues.push(`s-maxage=${env['CACHE_CONTROL_S_MAXAGE']}`); |
| 50 | } |
| 51 | |
| 52 | return headerValues.join(', '); |
| 53 | } |
no test coverage detected