All files / lib/internal/http cacheDirective.ts

78.26% Statements 18/23
8.33% Branches 1/12
25% Functions 1/4
78.26% Lines 18/23

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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 671x 1x             1x 1x 1x           1x     1x   1x 1x   1x   1x   1x     1x   1x   1x               1x   1x                   1x                      
import { pipe, SideEffect2 } from "@reactive-js/core/lib/functions";
import {
  CharStreamLike,
  optional,
  pEquals,
  parseWith,
  parseWithOrThrow,
} from "@reactive-js/core/lib/internal/parserCombinators";
import { isSome } from "@reactive-js/core/lib/option";
import { map, join } from "@reactive-js/core/lib/readonlyArray";
import {
  pToken,
  pTokenOrQuotedString,
  toTokenOrQuotedString,
  httpList,
} from "./httpGrammar";
import { getHeaderValue, HttpStandardHeader } from "./httpHeaders";
import { CacheDirective, HttpHeaders } from "./interfaces";
 
const pOptionalEquals = optional(pEquals);
 
const pCacheDirective = (charStream: CharStreamLike): CacheDirective => {
  const directive = pToken(charStream);
 
  const hasValue = isSome(pOptionalEquals(charStream));
 
  const value = hasValue ? pTokenOrQuotedString(charStream) : "";
 
  return { directive, value };
};
 
export const parseCacheDirective = parseWith(pCacheDirective);
 
export const parseCacheDirectiveOrThrow = parseWithOrThrow(pCacheDirective);
 
export const cacheDirectiveToString = ({
  directive,
  value,
}: CacheDirective): string =>
  value.length > 0
    ? `${directive}=${toTokenOrQuotedString(value)}`
    : `${directive}`;
 
const parseCacheDirectiveList = pipe(pCacheDirective, httpList, parseWith);
 
export const parseCacheControlFromHeaders = (
  headers: HttpHeaders,
): readonly CacheDirective[] => {
  const cacheControl = getHeaderValue(headers, HttpStandardHeader.CacheControl);
 
  return isSome(cacheControl)
    ? parseCacheDirectiveList(cacheControl) ?? []
    : [];
};
 
export const writeHttpCacheControlHeader = (
  cacheControl: readonly CacheDirective[],
  writeHeader: SideEffect2<string, string>,
) => {
  if (cacheControl.length > 0) {
    writeHeader(
      HttpStandardHeader.CacheControl,
      pipe(cacheControl, map(cacheDirectiveToString), join(",")),
    );
  }
};