@shifas7/response-handler
v1.0.1
Published
A TypeScript utility library for handling HTTP responses with standardized error handling and response formatting
Maintainers
Readme
Response Handler
A TypeScript utility library for handling HTTP responses with standardized error handling and response formatting. Perfect for Express.js applications that need consistent API response structures.
Features
- 🚀 Type-safe - Full TypeScript support with comprehensive type definitions
- 📦 Tree-shakable - Optimized exports for minimal bundle size
- 🎯 Express.js ready - Built specifically for Express.js applications
- 🔧 Standardized responses - Consistent API response format across your application
- 🛡️ Error handling - Built-in error handling with automatic Prisma error mapping
- 📄 Pagination support - Easy pagination metadata handling
- 🎨 Customizable - Flexible message customization and metadata support
- 📚 Well documented - Comprehensive JSDoc documentation
Installation
npm install @shifas7/response-handleryarn add @shifas7/response-handlerpnpm add @shifas7/response-handlerQuick Start
import express from 'express';
import ResponseHandler from '@shifas7/response-handler';
const app = express();
// Success response
app.get('/users', (req, res) => {
const users = [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }];
ResponseHandler.success(res, users, 'Users retrieved successfully');
});
// Error response
app.get('/users/:id', (req, res) => {
const user = null; // User not found
if (!user) {
return ResponseHandler.notFound(res, 'User not found');
}
ResponseHandler.success(res, user);
});
// Async handler with automatic error catching
app.get('/users/:id', ResponseHandler.asyncHandler(async (req, res) => {
const user = await getUserById(req.params.id);
ResponseHandler.success(res, user);
}));API Reference
ResponseHandler Class
The main class providing static methods for sending standardized HTTP responses.
Methods
success<T>(res, data?, message?, statusCode?, meta?)
Send a success response with optional data and metadata.
Parameters:
res- Express Response objectdata- Optional data payload (default: undefined)message- Success message (default: "Operation completed successfully")statusCode- HTTP status code (default: 200)meta- Optional metadata object
Example:
ResponseHandler.success(res, { id: 1, name: 'John' });
ResponseHandler.success(res, userData, 'User profile updated', 200, { version: '1.0' });error(res, message?, statusCode?, error?, data?)
Send an error response with optional error details.
Parameters:
res- Express Response objectmessage- Error message (default: "Internal server error")statusCode- HTTP status code (default: 500)error- Optional error details (string or object)data- Optional data payload (useful for partial success scenarios)
Example:
ResponseHandler.error(res, 'Something went wrong', 500);
ResponseHandler.error(res, 'Validation failed', 400, { field: 'email', message: 'Invalid format' });created<T>(res, data?, message?, meta?)
Send a created response (201) for successful resource creation.
Example:
ResponseHandler.created(res, newUser);
ResponseHandler.created(res, user, 'User account created successfully');noContent(res)
Send a no content response (204) for successful operations with no data.
Example:
ResponseHandler.noContent(res); // After successful deletionbadRequest(res, message?, error?)
Send a bad request response (400) for invalid client requests.
Example:
ResponseHandler.badRequest(res);
ResponseHandler.badRequest(res, 'Invalid email format', { field: 'email' });unauthorized(res, message?, error?)
Send an unauthorized response (401) for authentication failures.
Example:
ResponseHandler.unauthorized(res);
ResponseHandler.unauthorized(res, 'Invalid token');forbidden(res, message?, error?)
Send a forbidden response (403) for authorization failures.
Example:
ResponseHandler.forbidden(res);
ResponseHandler.forbidden(res, 'Insufficient permissions');notFound(res, message?, error?)
Send a not found response (404) for missing resources.
Example:
ResponseHandler.notFound(res);
ResponseHandler.notFound(res, 'User not found');conflict(res, message?, error?)
Send a conflict response (409) for resource conflicts.
Example:
ResponseHandler.conflict(res);
ResponseHandler.conflict(res, 'Email already exists');validationError(res, message?, error?)
Send a validation error response (422) for validation failures.
Example:
ResponseHandler.validationError(res);
ResponseHandler.validationError(res, 'Invalid input', {
email: 'Invalid email format',
password: 'Password too short'
});internalError(res, message?, error?)
Send an internal server error response (500) for server errors.
Example:
ResponseHandler.internalError(res);
ResponseHandler.internalError(res, 'Database connection failed');paginated<T>(res, data, pagination, message?)
Send a paginated response with pagination metadata.
Parameters:
res- Express Response objectdata- Array of data itemspagination- Pagination information object withpage,limit, andtotalmessage- Success message (default: "Operation completed successfully")
Example:
ResponseHandler.paginated(res, users, { page: 1, limit: 10, total: 100 });
ResponseHandler.paginated(res, products, pagination, 'Products retrieved successfully');asyncHandler(fn)
Async handler wrapper for Express route handlers to catch and handle errors automatically.
Features:
- Automatically handles Prisma errors (P2002, P2025)
- Handles validation errors
- Provides development vs production error details
Example:
app.get('/users', ResponseHandler.asyncHandler(async (req, res) => {
const users = await User.findMany();
ResponseHandler.success(res, users);
}));
app.get('/users/:id', ResponseHandler.asyncHandler(userController.getById));Response Interface
ApiResponse<T>
Standard API response interface for consistent response formatting.
interface ApiResponse<T = any> {
success: boolean;
message: string;
data?: T;
error?: string | object;
statusCode: number;
timestamp: string;
meta?: {
pagination?: {
page: number;
limit: number;
total: number;
totalPages: number;
};
[key: string]: any;
};
}HTTP Status Codes
HttpStatusCode
Enum containing common HTTP status codes for consistent usage.
enum HttpStatusCode {
OK = 200,
CREATED = 201,
NO_CONTENT = 204,
BAD_REQUEST = 400,
UNAUTHORIZED = 401,
FORBIDDEN = 403,
NOT_FOUND = 404,
CONFLICT = 409,
UNPROCESSABLE_ENTITY = 422,
INTERNAL_SERVER_ERROR = 500,
BAD_GATEWAY = 502,
SERVICE_UNAVAILABLE = 503,
}Response Messages
ResponseMessages(message?)
Factory function to generate common response messages with optional customization.
Example:
const messages = ResponseMessages('User');
// messages.CREATED = "User created successfully"
const defaultMessages = ResponseMessages();
// defaultMessages.SUCCESS = "Operation completed successfully"Advanced Usage
Custom Response Messages
import { ResponseMessages } from '@shifas7/response-handler';
const userMessages = ResponseMessages('User');
ResponseHandler.success(res, user, userMessages.CREATED);Error Handling with Prisma
The asyncHandler automatically maps common Prisma errors:
app.post('/users', ResponseHandler.asyncHandler(async (req, res) => {
const user = await prisma.user.create({
data: req.body
});
ResponseHandler.created(res, user);
}));
// P2002 (unique constraint violation) → 409 Conflict
// P2025 (record not found) → 404 Not FoundPagination Example
app.get('/users', ResponseHandler.asyncHandler(async (req, res) => {
const page = parseInt(req.query.page as string) || 1;
const limit = parseInt(req.query.limit as string) || 10;
const skip = (page - 1) * limit;
const [users, total] = await Promise.all([
prisma.user.findMany({ skip, take: limit }),
prisma.user.count()
]);
ResponseHandler.paginated(res, users, { page, limit, total });
}));Custom Metadata
ResponseHandler.success(res, data, 'Data retrieved', 200, {
version: '1.0',
cache: 'miss',
processingTime: '150ms'
});Response Format
All responses follow this standardized format:
Success Response
{
"success": true,
"message": "Operation completed successfully",
"data": { "id": 1, "name": "John" },
"statusCode": 200,
"timestamp": "2024-01-15T10:30:00.000Z",
"meta": {
"pagination": {
"page": 1,
"limit": 10,
"total": 100,
"totalPages": 10
}
}
}Error Response
{
"success": false,
"message": "User not found",
"error": "User with ID 123 does not exist",
"statusCode": 404,
"timestamp": "2024-01-15T10:30:00.000Z"
}TypeScript Support
This library is written in TypeScript and provides full type definitions. Import types as needed:
import ResponseHandler, {
ApiResponse,
HttpStatusCode,
ResponseMessages
} from '@shifas7/response-handler';
// Type your responses
const response: ApiResponse<User[]> = {
success: true,
message: 'Users retrieved',
data: users,
statusCode: HttpStatusCode.OK,
timestamp: new Date().toISOString()
};Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Changelog
1.0.0
- Initial release
- Complete TypeScript support
- Express.js integration
- Standardized response format
- Error handling utilities
- Pagination support
- Async handler wrapper
