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.

49 lines (40 loc) 1.39 kB
import { Response } from 'express'; interface SuccessResponse<T = any> { statusCode: number; status: boolean; message: string; data?: T; } export class ApiResponse<T = any> { public statusCode: number; public message: string; public data: T; public status: boolean; constructor(statusCode: number, data: T, message = 'success') { this.statusCode = statusCode; this.message = message; this.data = data; this.status = statusCode < 400; } toJSON(): SuccessResponse<T> { const response: SuccessResponse<T> = { statusCode: this.statusCode, status: this.status, message: this.message, }; if (this.data !== undefined && this.data !== null) { response.data = this.data; } return response; } } export const SuccessResponse = <T>( res: Response, statusCode: number, data: T, message: string ) => { const apiResponse = new ApiResponse<T>(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()); };