All files / plainweb/src handler.ts

70.83% Statements 17/24
60% Branches 3/5
100% Functions 1/1
70.83% Lines 17/24

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 591x             1x                                           4x 4x 4x         4x 4x 1x 1x 3x 3x 3x       3x   3x 3x 3x             4x  
import type express from "express";
import {
  type PlainResponse,
  html,
  isPlainResponse,
  json,
  sendPlainResponse,
} from "./plain-response";
 
export interface HandlerArgs {
  req: express.Request;
  res: express.Response;
}
 
export type JSONSerializable =
  | string
  | number
  | boolean
  | null
  | JSONSerializable[]
  | { [key: string]: JSONSerializable };
 
export type Handler = (
  args: HandlerArgs,
) => Promise<ExpressResponse | PlainResponse | JSX.Element | JSONSerializable>;
 
// escape hatch so users can use the express.Response API directly
export type ExpressResponse = () => void;
 
export async function handleResponse(
  res: express.Response,
  userResponse:
    | PlainResponse
    | JSX.Element
    | JSONSerializable
    | ExpressResponse,
) {
  if (isPlainResponse(userResponse)) {
    await sendPlainResponse(res, userResponse);
  } else if (
    typeof userResponse === "string" ||
    (typeof userResponse === "object" && userResponse instanceof Promise)
  ) {
    // assume it's a JSX.Element
    await sendPlainResponse(res, html(userResponse));
    return;
  } else if (typeof userResponse === "object") {
    // assume it's a JSON
    await sendPlainResponse(res, json(userResponse));
    return;
  } else if (typeof userResponse === "function") {
    // assume it's an express response
    userResponse();
    return;
  } else {
    throw new Error("Unexpected response type");
  }
}