UNPKG

node-js-api-response-ts

Version:

Unified API response and error handling for Express.js in TypeScript. This package provides a middleware for consistent API responses and error handling in Express applications, making it easier to manage API responses and errors in a standardized way.

35 lines (34 loc) 1.17 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SuccessResponse = exports.ApiResponse = void 0; class ApiResponse { constructor(statusCode, data, message = 'success') { this.statusCode = statusCode; this.message = message; this.data = data; this.status = statusCode < 400; } toJSON() { const response = { statusCode: this.statusCode, status: this.status, message: this.message, }; if (this.data !== undefined && this.data !== null) { response.data = this.data; } return response; } } exports.ApiResponse = ApiResponse; const SuccessResponse = (res, statusCode, data, message) => { const apiResponse = new ApiResponse(statusCode, data, message); // const response: SuccessResponse<T> = { // statusCode: result.statusCode, // message: result.message, // status: result.status, // ...(data !== undefined && data !== null && { data: result.data }) // }; res.status(statusCode).json(apiResponse.toJSON()); }; exports.SuccessResponse = SuccessResponse;