All files / common apiResponse.ts

80% Statements 16/20
66.66% Branches 2/3
60% Functions 6/10
80% Lines 16/20

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 651x 1x 1x 1x 1x 1x 1x     1x   6x 6x 6x 6x       6x                         1x       2x             3x                                            
export enum HttpStatus {
  OK = 200,
  CREATED = 201,
  NO_CONTENT = 204,
  BAD_REQUEST = 400,
  NOT_FOUND = 404,
  INTERNAL_ERROR = 500,
}
 
export class ApiResponse {
  constructor(
    public statusCode: number,
    public body: string,
    public headers?: Record<string, string>,
    public isBase64Encoded?: boolean
  ) {}
 
  static json(statusCode: number, payload: unknown): ApiResponse {
    return new ApiResponse(statusCode, JSON.stringify(payload), {
      'Content-Type': 'application/json',
    });
  }
 
  static no_content(payload: unknown): ApiResponse {
    return ApiResponse.json(HttpStatus.NO_CONTENT, payload);
  }
  static ok(payload: unknown): ApiResponse {
    return ApiResponse.json(HttpStatus.OK, payload);
  }
 
  static created(payload: unknown): ApiResponse {
    return ApiResponse.json(HttpStatus.CREATED, payload);
  }
 
  static badRequest(message: string): ApiResponse {
    return ApiResponse.json(HttpStatus.BAD_REQUEST, {
      success: false,
      error: message,
    });
  }
 
  static notFound(message: string): ApiResponse {
    return ApiResponse.json(HttpStatus.NOT_FOUND, {
      success: false,
      error: message,
    });
  }
 
  static internalError(message: string = 'Internal Server Error'): ApiResponse {
    return ApiResponse.json(HttpStatus.INTERNAL_ERROR, {
      success: false,
      error: message,
    });
  }
 
  static binary(buffer: Buffer, contentType: string): ApiResponse {
    return new ApiResponse(
      HttpStatus.OK,
      buffer.toString('base64'),
      { 'Content-Type': contentType },
      true
    );
  }
}