All files / server/src/middleware logApiCall.ts

88% Statements 22/25
56.25% Branches 9/16
100% Functions 3/3
88% Lines 22/25

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      39x 3803x 272x   3803x 3803x     3803x 3472x   3606x 59x   3603x           39x         5223x 1413x 1413x     5223x 3810x 3803x 3803x 3803x 3803x 3803x       3810x    
import { Request, Response, NextFunction } from "express";
import { logger } from "server/utils/logger";
 
const formatSize = (header: string | undefined): string => {
  Iif (header === undefined) {
    return "-";
  }
  const bytes = Number(header);
  Iif (!Number.isFinite(bytes)) {
    return header;
  }
  if (bytes < 1024) {
    return `${bytes} B`;
  }
  Eif (bytes < 1024 * 1024) {
    return `${(bytes / 1024).toFixed(1)} KB`;
  }
  if (bytes < 1024 * 1024 * 1024) {
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  }
  return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
};
 
export const logApiCall = (
  req: Request,
  res: Response,
  next: NextFunction,
): void => {
  Iif (req.method === "OPTIONS") {
    next();
    return;
  }
 
  const start = Date.now();
  res.on("finish", () => {
    const ms = Date.now() - start;
    const user = req.auth?.username ?? "anon";
    const ip = req.ip?.replace(/^::ffff:/, "") ?? "-";
    const size = formatSize(res.get("Content-Length"));
    logger.info(
      `API call: ${req.method} ${req.path} ${res.statusCode} ${ms}ms user=${user} ip=${ip} size=${size}`,
    );
  });
  next();
};