All files / lib/internal/http HttpMessage.ts

35.71% Statements 10/28
0% Branches 0/9
0% Functions 0/4
35.71% Lines 10/28

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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82  1x 1x 1x 1x 1x 1x     1x                                 1x                                                     1x                                         1x              
import { SideEffect2 } from "@reactive-js/core/lib/functions";
import { IOSourceLike, fromValue } from "@reactive-js/core/lib/io";
import { isSome, isNone } from "@reactive-js/core/lib/option";
import { writeHttpCacheControlHeader } from "./cacheDirective";
import { writeHttpContentInfoHeaders } from "./httpContentInfo";
import { writeHttpHeaders } from "./httpHeaders";
import { writeHttpPreferenceHeaders } from "./httpPreferences";
import { HttpMessage } from "./interfaces";
 
export const writeHttpMessageHeaders = <T>(
  { cacheControl, contentInfo, headers, preferences }: HttpMessage<T>,
  writeHeader: SideEffect2<string, string>,
): void => {
  writeHttpCacheControlHeader(cacheControl, writeHeader);
 
  if (isSome(contentInfo)) {
    writeHttpContentInfoHeaders(contentInfo, writeHeader);
  }
 
  if (isSome(preferences)) {
    writeHttpPreferenceHeaders(preferences, writeHeader);
  }
 
  writeHttpHeaders(headers, writeHeader);
};
 
export const encodeHttpMessageWithUtf8 = ({
  contentInfo,
  ...msg
}: HttpMessage<string>): HttpMessage<Uint8Array> => {
  if (isNone(contentInfo)) {
    throw new Error("HttpMessage has not contentInfo");
  }
 
  const { contentType } = contentInfo;
  const textEncoder = new TextEncoder();
 
  return {
    ...msg,
    body: textEncoder.encode(msg.body),
    contentInfo: {
      ...contentInfo,
      contentType: {
        ...contentType,
        params: {
          ...contentType.params,
          charset: "utf-8",
        },
      },
    },
  };
};
 
export const decodeHttpMessageWithCharset = ({
  contentInfo,
  ...msg
}: HttpMessage<Uint8Array>): HttpMessage<string> => {
  if (isNone(contentInfo)) {
    return {
      ...msg,
      body: "",
    };
  } else {
    const { charset = "utf-8" } = contentInfo.contentType.params;
    const textDecoder = new TextDecoder(charset);
    const body = textDecoder.decode(msg.body);
 
    return {
      ...msg,
      body,
    };
  }
};
 
export const toIOSourceHttpMessage = <TBody>({
  body,
  ...msg
}: HttpMessage<TBody>): HttpMessage<IOSourceLike<TBody>> => ({
  ...msg,
  body: fromValue()(body),
});