All files / proxy/utils cache-control.ts

100% Statements 15/15
100% Branches 2/2
100% Functions 3/3
100% Lines 15/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 248x 8x   8x 9x 9x 9x       18x 18x 39x   18x 6x   12x 12x 12x   18x    
const CACHE_MAX_AGE = 3600
const SHARED_CACHE_MAX_AGE = 60
 
export function updateCacheControlHeader(headerValue: string): string {
  headerValue = updateCacheControlAge(headerValue, 'max-age', CACHE_MAX_AGE)
  headerValue = updateCacheControlAge(headerValue, 's-maxage', SHARED_CACHE_MAX_AGE)
  return headerValue
}
 
function updateCacheControlAge(headerValue: string, type: 'max-age' | 's-maxage', cacheMaxAge: number): string {
  const cacheControlDirectives = headerValue.split(', ')
  const maxAgeIndex = cacheControlDirectives.findIndex(
    (directive) => directive.split('=')[0].trim().toLowerCase() === type
  )
  if (maxAgeIndex === -1) {
    cacheControlDirectives.push(`${type}=${cacheMaxAge}`)
  } else {
    const oldMaxAge = Number(cacheControlDirectives[maxAgeIndex].split('=')[1])
    const newMaxAge = Math.min(cacheMaxAge, oldMaxAge)
    cacheControlDirectives[maxAgeIndex] = `${type}=${newMaxAge}`
  }
  return cacheControlDirectives.join(', ')
}