All files / proxy/utils cacheControl.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 24 25 26 274x 4x   4x 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 {
  let result = updateCacheControlAge(headerValue, 'max-age', CACHE_MAX_AGE)
  result = updateCacheControlAge(result, 's-maxage', SHARED_CACHE_MAX_AGE)
 
  return result
}
 
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(', ')
}