All files / src/utils getCacheControlHeaderWithMaxAgeIfLower.ts

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

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  22x 49x   22x 6x   16x 16x 16x       12x         11x   11x 11x   11x    
function setDirective(directives: string[], directive: 'max-age' | 's-maxage', maxMaxAge: number) {
  const directiveIndex = directives.findIndex(
    (directivePair) => directivePair.split('=')[0].trim().toLowerCase() === directive
  )
  if (directiveIndex === -1) {
    directives.push(`${directive}=${maxMaxAge}`)
  } else {
    const oldValue = Number(directives[directiveIndex].split('=')[1])
    const newValue = Math.min(maxMaxAge, oldValue)
    directives[directiveIndex] = `${directive}=${newValue}`
  }
}
 
export function getCacheControlHeaderWithMaxAgeIfLower(
  cacheControlHeaderValue: string,
  maxMaxAge: number,
  maxSMaxAge: number
): string {
  const cacheControlDirectives = cacheControlHeaderValue.split(', ')
 
  setDirective(cacheControlDirectives, 'max-age', maxMaxAge)
  setDirective(cacheControlDirectives, 's-maxage', maxSMaxAge)
 
  return cacheControlDirectives.join(', ')
}