All files / src Request.ts

86.2% Statements 50/58
89.47% Branches 17/19
87.5% Functions 7/8
86.2% Lines 50/58

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 741x   1x     1x 20x 20x   1x 3x 3x 1x 1x 1x 1x   2x 3x   1x 25x 25x           25x 25x   1x 45x 45x 35x 45x 10x 10x 45x   1x       1x 12x 12x 1x 1x 1x 1x   11x 12x   1x 33x 33x 9x 9x   24x 33x       24x 33x   1x 33x 33x 1x  
import { Request } from "express";
import { RequestParamError } from "@/Error";
export class RequestDataParser {
  private req: Request;
 
  constructor(req: Request) {
    this.req = req;
  }
 
  getHeaderAsString(key: string): string {
    const value = this.req.get(key);
    if (!value) {
      throw new RequestParamError(
        `${key} is required header but was not found`
      );
    }
 
    return value;
  }
 
  getPathParamAsString(key: string): string {
    const value = this.req.params[key];
    if (!value) {
      throw new RequestParamError(
        `${key} is required path param but was not found`
      );
    }
 
    return value;
  }
 
  getQueryParamAsStringOrUndefined(key: string): string | undefined {
    const value = this.req.query[key];
    if (typeof value === "string") {
      return value;
    } else {
      return undefined;
    }
  }
 
  getQueryParamAsStringWithDefault(key: string, def: string): string {
    return this.getQueryParamAsStringOrUndefined(key) || def;
  }
 
  getQueryParamAsString(key: string): string {
    const value = this.getQueryParamAsStringOrUndefined(key);
    if (!value) {
      throw new RequestParamError(
        `${key} is required query param but was not found`
      );
    }
 
    return value;
  }
 
  getQueryParamAsNumberOrUndefined(key: string): number | undefined {
    const value = this.getQueryParamAsStringOrUndefined(key);
    if (value === undefined) {
      return undefined;
    }
 
    const numberValue = Number(value);
    if (isNaN(numberValue)) {
      throw new RequestParamError(`${key} should be a number`);
    }
 
    return numberValue;
  }
 
  getQueryParamAsNumberWithDefault(key: string, def: number): number {
    return this.getQueryParamAsNumberOrUndefined(key) || def;
  }
}