npm package: @smmorshed/express-utils
Description: A collection of TypeScript utilities for Express.js applications
Author: Your Name
Latest version: 1.0.0
Deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.

# Express Utils

A comprehensive collection of TypeScript utilities for Express.js applications, providing authentication, validation, middleware, and response handling.

## Installation

```bash
npm install @your-username/express-utils
```

Note: This package has a peer dependency on Express.js:

```bash
npm install express
```

## Features

- **Middleware**: Request logging, CORS handling, and error handling
- **Authentication**: JWT-based authentication utilities
- **Validation**: Request body and query parameter validation
- **Response Handling**: Standardized API responses

## Usage Examples

### Basic Middleware

```typescript
import express from 'express';
import { requestLogger, corsMiddleware, errorHandler } from '@your-username/express-utils';

const app = express();

// Apply middleware
app.use(express.json());
app.use(requestLogger);
app.use(corsMiddleware);

// Your routes here
app.get('/api/hello', (req, res) => {
  res.json({ message: 'Hello World' });
});

// Error handling middleware (should be last)
app.use(errorHandler);

app.listen(3000, () => {
  console.log('Server running on port 3000');
});
```

### Validation

```typescript
import express from 'express';
import { validateBody, validateQuery } from '@your-username/express-utils';

const app = express();
app.use(express.json());

// Validate request body
app.post('/api/users', 
  validateBody([
    { field: 'username', required: true, type: 'string', minLength: 3, maxLength: 20 },
    { field: 'email', required: true, type: 'string', pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/ },
    { field: 'age', type: 'number', min: 18 }
  ]),
  (req, res) => {
    // Request body is valid at this point
    res.status(201).json({ success: true, data: req.body });
  }
);

// Validate query parameters
app.get('/api/products',
  validateQuery([
    { field: 'category', required: true },
    { field: 'limit', type: 'number', min: 1, max: 100 }
  ]),
  (req, res) => {
    // Query parameters are valid at this point
    res.json({ success: true, data: [] });
  }
);
```

### Authentication

```typescript
import express from 'express';
import { AuthUtils } from '@your-username/express-utils';

const app = express();
app.use(express.json());

// Create authentication utility
const auth = new AuthUtils({ 
  tokenSecret: 'your-secret-key',
  tokenExpiration: '1d' // 1 day
});

// Login route to generate token
app.post('/api/login', (req, res) => {
  // Validate credentials (your implementation)
  if (req.body.username === 'admin' && req.body.password === 'password') {
    // Generate token
    const token = auth.generateToken({ 
      userId: 1,
      username: req.body.username,
      role: 'admin'
    });
    
    res.json({ success: true, token });
  } else {
    res.status(401).json({ success: false, message: 'Invalid credentials' });
  }
});

// Protected route using JWT authentication
app.get('/api/protected', 
  auth.authenticateJWT(),
  (req, res) => {
    // The user is authenticated at this point
    // Access user data from req.user
    res.json({ 
      success: true, 
      message: 'Protected data',
      user: (req as any).user 
    });
  }
);
```

### Response Utility

```typescript
import express from 'express';
import { sendResponse } from '@your-username/express-utils';

const app = express();

app.get('/api/users/:id', (req, res) => {
  const user = { id: req.params.id, name: 'John Doe' };
  
  return sendResponse(res, 200, user, 'User retrieved successfully');
});

app.post('/api/users', (req, res) => {
  // Create user logic
  return sendResponse(res, 201, { id: 123 }, 'User created successfully');
});

app.use((req, res) => {
  return sendResponse(res, 404, null, 'Route not found');
});
```

### Rate Limiting

```typescript
import express from 'express';
import { createRateLimiter } from '@your-username/express-utils';

const app = express();

// Create a rate limiter (100 requests per minute)
const rateLimiter = createRateLimiter({ 
  windowMs: 60000, // 1 minute
  maxRequests: 100
});

// Apply to all routes
app.use(rateLimiter);

// Or apply to specific routes
app.get('/api/limited',
  createRateLimiter({ windowMs: 60000, maxRequests: 10 }),
  (req, res) => {
    res.json({ message: 'Rate limited endpoint' });
  }
);
```

## API Documentation

### Middleware

- `requestLogger`: Logs all incoming requests with timestamp, method, and URL
- `corsMiddleware`: Handles CORS headers and preflight requests
- `errorHandler`: Global error handling middleware
- `createRateLimiter`: Creates a rate limiting middleware

### Validation

- `validateBody`: Validates request body against specified rules
- `validateQuery`: Validates query parameters against specified rules

### Authentication

- `AuthUtils`: Class for JWT authentication with methods:
  - `generateToken`: Creates a new JWT token
  - `verifyToken`: Verifies a JWT token
  - `authenticateJWT`: Middleware to protect routes

### Response

- `sendResponse`: Helper to create consistent API responses

## License

MIT