Skip to content

Coderkube-App/api-response-handler

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

9 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸš€ API Response Handler

A lightweight, highly robust, and standardized API response handler for Node.js and Express applications. It effortlessly guarantees a clean, consistent, and predictable response structure across your entire API architecture.


✨ Features

  • πŸ’Ž Standardized Format: Uniform success, error, and paginated responses.
  • ⚑ Lightweight & Fast: Zero external runtime dependencies.
  • πŸ“ˆ Smart Pagination: Built-in calculation for pages, limits, total items, and next/prev status indicators.
  • πŸ›‘οΈ TypeScript Ready: Full type definitions out of the box with IApiResponse.
  • πŸŽ›οΈ Extremely Flexible: Custom metadata and dynamic error payloads supported.

βš™οΈ Requirements

  • Runtime: Node.js >= 12.0.0 (Works in almost any modern Node environment)
  • Development & Testing: Node.js >= 18.0.0 (Required for the native node:test suite)

πŸ“¦ Installation

Install the package via your favorite package manager:

# Using npm
npm install standard-api-response-handler

# Using yarn
yarn add standard-api-response-handler

# Using pnpm
pnpm add standard-api-response-handler

πŸ› οΈ Quick Start & Usage

1. Standard Success Response

Quickly send successful responses with data, optional custom messages, and custom HTTP status codes (defaults to 200).

const ApiResponse = require('standard-api-response-handler').default;

app.get('/api/users/:id', async (req, res) => {
  const user = { id: 42, username: 'dev_hero' };
  
  // Sends a standard 200 OK response
  return ApiResponse.success(res, user, 'User profile fetched successfully');
});

Response Payload:

{
  "success": true,
  "status": 200,
  "message": "User profile fetched successfully",
  "data": {
    "id": 42,
    "username": "dev_hero"
  }
}

2. Robust Error Response

Consistently catch and format error responses. Supports custom HTTP status codes (defaults to 500) and optional validation/error payload arrays.

const ApiResponse = require('standard-api-response-handler').default;

app.post('/api/register', (req, res) => {
  const errors = { email: 'Email address is invalid' };
  
  // Sends a standard 400 Bad Request with details
  return ApiResponse.error(res, 'Validation failed', 400, errors);
});

Response Payload:

{
  "success": false,
  "status": 400,
  "message": "Validation failed",
  "errors": {
    "email": "Email address is invalid"
  }
}

3. Created Response (201)

Quickly send standard 201 Created responses when a new resource is successfully created.

const ApiResponse = require('standard-api-response-handler').default;

app.post('/api/users', async (req, res) => {
  const newUser = { id: 43, username: 'new_coder' };
  
  // Sends a standard 201 Created response
  return ApiResponse.created(res, newUser, 'User created successfully');
});

Response Payload:

{
  "success": true,
  "status": 201,
  "message": "User created successfully",
  "data": {
    "id": 43,
    "username": "new_coder"
  }
}

4. Not Found Response (404)

Quickly send standard 404 Not Found responses when a requested resource is not found.

const ApiResponse = require('standard-api-response-handler').default;

app.get('/api/users/:id', async (req, res) => {
  // If user is not found in database
  return ApiResponse.notFound(res, 'User not found');
});

Response Payload:

{
  "success": false,
  "status": 404,
  "message": "User not found"
}

5. Smart Paginated Response

Pass your raw data array and pagination metrics, and let the handler auto-calculate all structural parameters (total pages, current page, limits, and next/prev page flags).

const ApiResponse = require('standard-api-response-handler').default;

app.get('/api/products', async (req, res) => {
  const page = parseInt(req.query.page) || 1;
  const limit = parseInt(req.query.limit) || 10;
  
  const { products, totalCount } = await db.products.findAndCount({ page, limit });
  
  // Auto-calculates metadata and sends pagination
  return ApiResponse.paginate(res, products, page, limit, totalCount, 'Products retrieved successfully');
});

Response Payload:

{
  "success": true,
  "status": 200,
  "message": "Products retrieved successfully",
  "data": [
    { "id": 1, "name": "Premium Keyboard" },
    { "id": 2, "name": "Ergonomic Mouse" }
  ],
  "meta": {
    "currentPage": 1,
    "itemsPerPage": 10,
    "totalItems": 45,
    "totalPages": 5,
    "hasNextPage": true,
    "hasPrevPage": false
  }
}

6. πŸ¦• TypeScript Usage

Fully compatible with TypeScript projects out-of-the-box. Import the helper class and leverage standard typings.

import ApiResponse, { IApiResponse } from 'standard-api-response-handler';
import { Request, Response } from 'express';

interface User {
  id: number;
  email: string;
}

export const getUserProfile = (req: Request, res: Response) => {
  const user: User = { id: 1, email: 'admin@dev.io' };
  
  // Fully typed method signatures
  return ApiResponse.success(res, user, 'Profile loaded');
};

πŸ“– API Reference

ApiResponse.success(res, data, message, statusCode, meta)

Parameter Type Required Default Description
res Response Yes β€” Express-like Response Object
data any No null The actual payload data to return
message string No 'Success' User-friendly message for feedback
statusCode number No 200 HTTP Status Code to return
meta any No null Optional custom metadata object

ApiResponse.error(res, message, statusCode, errors)

Parameter Type Required Default Description
res Response Yes β€” Express-like Response Object
message string No 'Internal Server Error' Human-readable error description
statusCode number No 500 HTTP Status Code to return
errors any No null Detailed validation errors or system debug errors

ApiResponse.paginate(res, data, page, limit, totalItems, message)

Parameter Type Required Default Description
res Response Yes β€” Express-like Response Object
data any[] Yes β€” Array of items for the current page
page number Yes β€” Active page index (1-based)
limit number Yes β€” Number of items per page
totalItems number Yes β€” Total item count matching the query in database
message string No 'Data retrieved successfully' Summary success description

πŸ’‘ Specialized Status Code Helper Methods

For cleaner, more semantic code, the library provides helper methods for common HTTP status codes.

Success Responses (2xx)

  • ApiResponse.created(res, data, message, meta) (201 Created)
  • ApiResponse.accepted(res, data, message, meta) (202 Accepted)
  • ApiResponse.noContent(res) (204 No Content - returns no response body)

Usage Example:

// Send a 201 Created response
ApiResponse.created(res, { id: 42 }, 'Resource created successfully');

// Send a 204 No Content response
ApiResponse.noContent(res);

Client Error Responses (4xx)

  • ApiResponse.badRequest(res, message, errors) (400 Bad Request)
  • ApiResponse.unauthorized(res, message, errors) (401 Unauthorized)
  • ApiResponse.forbidden(res, message, errors) (403 Forbidden)
  • ApiResponse.notFound(res, message, errors) (404 Not Found)
  • ApiResponse.methodNotAllowed(res, message, errors) (405 Method Not Allowed)
  • ApiResponse.conflict(res, message, errors) (409 Conflict)
  • ApiResponse.unprocessableEntity(res, message, errors) (422 Unprocessable Entity)
  • ApiResponse.tooManyRequests(res, message, errors) (429 Too Many Requests)

Usage Example:

// Send a 403 Forbidden response
ApiResponse.forbidden(res, 'You do not have access to this resource');

// Send a 422 Unprocessable Entity response with details
ApiResponse.unprocessableEntity(res, 'Validation failed', { email: 'Email already exists' });

Server Error Responses (5xx)

  • ApiResponse.internalServerError(res, message, errors) (500 Internal Server Error)
  • ApiResponse.notImplemented(res, message, errors) (501 Not Implemented)
  • ApiResponse.badGateway(res, message, errors) (502 Bad Gateway)
  • ApiResponse.serviceUnavailable(res, message, errors) (503 Service Unavailable)
  • ApiResponse.gatewayTimeout(res, message, errors) (504 Gateway Timeout)

Usage Example:

// Send a 503 Service Unavailable response
ApiResponse.serviceUnavailable(res, 'Database connection lost', databaseError);

πŸͺͺ License

This project is licensed under the MIT License - see the LICENSE file for details.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors