npm package: @shifas7/response-handler
Description: A TypeScript utility library for handling HTTP responses with standardized error handling and response formatting
Author: Shifas
Latest version: 1.0.1

# Response Handler

[![npm version](https://badge.fury.io/js/@shifas7/response-handler.svg)](https://badge.fury.io/js/@shifas7/response-handler)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![TypeScript](https://img.shields.io/badge/%3C%2F%3E-TypeScript-%230074c1.svg)](https://www.typescriptlang.org/)

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

```bash
npm install @shifas7/response-handler
```

```bash
yarn add @shifas7/response-handler
```

```bash
pnpm add @shifas7/response-handler
```

## Quick Start

```typescript
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 object
- `data` - Optional data payload (default: undefined)
- `message` - Success message (default: "Operation completed successfully")
- `statusCode` - HTTP status code (default: 200)
- `meta` - Optional metadata object

**Example:**
```typescript
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 object
- `message` - 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:**
```typescript
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:**
```typescript
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:**
```typescript
ResponseHandler.noContent(res); // After successful deletion
```

##### `badRequest(res, message?, error?)`

Send a bad request response (400) for invalid client requests.

**Example:**
```typescript
ResponseHandler.badRequest(res);
ResponseHandler.badRequest(res, 'Invalid email format', { field: 'email' });
```

##### `unauthorized(res, message?, error?)`

Send an unauthorized response (401) for authentication failures.

**Example:**
```typescript
ResponseHandler.unauthorized(res);
ResponseHandler.unauthorized(res, 'Invalid token');
```

##### `forbidden(res, message?, error?)`

Send a forbidden response (403) for authorization failures.

**Example:**
```typescript
ResponseHandler.forbidden(res);
ResponseHandler.forbidden(res, 'Insufficient permissions');
```

##### `notFound(res, message?, error?)`

Send a not found response (404) for missing resources.

**Example:**
```typescript
ResponseHandler.notFound(res);
ResponseHandler.notFound(res, 'User not found');
```

##### `conflict(res, message?, error?)`

Send a conflict response (409) for resource conflicts.

**Example:**
```typescript
ResponseHandler.conflict(res);
ResponseHandler.conflict(res, 'Email already exists');
```

##### `validationError(res, message?, error?)`

Send a validation error response (422) for validation failures.

**Example:**
```typescript
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:**
```typescript
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 object
- `data` - Array of data items
- `pagination` - Pagination information object with `page`, `limit`, and `total`
- `message` - Success message (default: "Operation completed successfully")

**Example:**
```typescript
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:**
```typescript
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.

```typescript
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.

```typescript
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:**
```typescript
const messages = ResponseMessages('User');
// messages.CREATED = "User created successfully"

const defaultMessages = ResponseMessages();
// defaultMessages.SUCCESS = "Operation completed successfully"
```

## Advanced Usage

### Custom Response Messages

```typescript
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:

```typescript
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 Found
```

### Pagination Example

```typescript
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

```typescript
ResponseHandler.success(res, data, 'Data retrieved', 200, {
  version: '1.0',
  cache: 'miss',
  processingTime: '150ms'
});
```

## Response Format

All responses follow this standardized format:

### Success Response
```json
{
  "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
```json
{
  "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:

```typescript
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](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