All files / http JsonResponse.ts

100% Statements 11/11
100% Branches 0/0
100% Functions 5/5
100% Lines 11/11

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            1x   5x               5x                   5x                   2x 2x                   2x 2x               4x 4x 4x    
import { ServerResponse } from 'http';
 
/**
 * @class JsonResponse
 * @description A helper class for creating JSON responses.
 */
export class JsonResponse {
  private _body: any;
  private _statusCode: number = 200;
  private res: ServerResponse;
 
  /**
   * @constructor
   * @param {ServerResponse} res - The server response object.
   */
  private constructor(res: ServerResponse) {
    this.res = res;
  }
 
  /**
   * @method for
   * @description Creates a new JsonResponse instance.
   * @param {ServerResponse} res - The server response object.
   * @returns {JsonResponse} A new JsonResponse instance.
   */
  public static for(res: ServerResponse): JsonResponse {
    return new JsonResponse(res);
  }
 
  /**
   * @method status
   * @description Sets the status code of the response.
   * @param {number} status - The status code.
   * @returns {this} The JsonResponse instance.
   */
  public status(status: number): this {
    this._statusCode = status;
    return this;
  }
 
  /**
   * @method body
   * @description Sets the body of the response.
   * @param {any} data - The data to send in the response.
   * @returns {this} The JsonResponse instance.
   */
  public body(data: any): this {
    this._body = data;
    return this;
  }
 
  /**
   * @method send
   * @description Sends the response.
   */
  public send(): void {
    this.res.statusCode = this._statusCode;
    this.res.setHeader('Content-Type', 'application/json');
    this.res.end(JSON.stringify(this._body));
  }
}