All files / src/server server.ts

0% Statements 0/32
0% Branches 0/21
0% Functions 0/8
0% Lines 0/32

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                                                                                                                                         
import { Server, ServerResponse } from "http";
import bodyParser from "body-parser";
import express, { ErrorRequestHandler, RequestHandler, Response } from "express";
import morgan from "morgan";
import { logger } from "../logger";
import { cleanupBody } from "../utils";
import { RequestExt } from "./request-ext";
 
export interface MockApiServerConfig {
  port: number;
}
 
const errorHandler: ErrorRequestHandler = (err, _req, res, _next) => {
  logger.error("Error", err);
 
  const errResponse = err.toJSON
    ? err.toJSON()
    : err instanceof Error
      ? { name: err.name, message: err.message, stack: err.stack }
      : err;
 
  res.status(err.status || 500);
  res.contentType("application/json").send(errResponse).end();
};
 
const rawBodySaver = (req: RequestExt, res: ServerResponse, buf: Buffer, encoding: BufferEncoding) => {
  Iif (buf && buf.length) {
    req.rawBody = cleanupBody(buf.toString(encoding || "utf8"));
  }
};
 
const loggerstream = {
  write: (message: string) => logger.info(message),
};
 
export class MockApiServer {
  private app: express.Application;
 
  constructor(private config: MockApiServerConfig) {
    this.app = express();
    this.app.use(morgan("dev", { stream: loggerstream }));
    this.app.use(bodyParser.json({ verify: rawBodySaver, strict: false }));
    this.app.use(bodyParser.urlencoded({ verify: rawBodySaver, extended: true }));
    this.app.use(bodyParser.text({ type: "*/xml", verify: rawBodySaver }));
    this.app.use(bodyParser.text({ type: "*/pdf", verify: rawBodySaver }));
    this.app.use(bodyParser.text({ type: "text/plain" }));
    this.app.use(bodyParser.raw({ type: "application/octet-stream", limit: "10mb" }));
  }
 
  public use(route: string, ...handlers: RequestHandler[]): void {
    this.app.use(route, ...handlers);
  }
 
  public start(): void {
    this.app.use(errorHandler);
 
    const server = this.app.listen(this.config.port, () => {
      logger.info(`Started server on ${getAddress(server)}`);
    });
  }
}
 
export type ServerRequestHandler = (request: RequestExt, response: Response) => void;
 
const getAddress = (server: Server): string => {
  const address = server?.address();
  return typeof address === "string" ? "pipe " + address : "port " + address?.port;
};