@thalorlabs/middleware
Version:
Express.js middleware collection for TypeScript applications with authentication, logging, and error handling
203 lines (172 loc) ⢠6.69 kB
Markdown
# DOCSTYLE.md ā @thalorlabs/middleware
š JSDoc Standards for Middleware Components
This document defines the standards for documenting middleware components in @thalorlabs/middleware. The goal is to make middleware easy to understand, maintain, and use across projects while keeping the docs concise and informative.
## 1. General Rules
- **Keep it clear**: middleware components should have descriptive, concise docs.
- **Include**:
- Description (what the middleware does and when to use it)
- `@example` with common usage patterns
- Configuration options and error handling
- **Exclude**:
- Owners, version numbers, dates ā track via git and package.json
- Use `@remarks` sparingly, only for non-obvious behavior or constraints.
### Middleware Component Policy
**This package only contains ThalorLabs middleware components** - standardized middleware for our applications.
- ā
Document: `protect`, `TryCatchMiddleware`, `protectedAccessMiddleware` (our middleware contracts)
- ā Never document: Third-party library middleware, framework-specific middleware
- Keep application-specific middleware logic local to the service that uses it
## 2. Template
```typescript
/**
* Brief description of what the middleware does and when to use it.
*
* Additional details about configuration options, error handling, and usage scenarios.
*
* @example
* app.use('/api', yourMiddleware(options));
*
* app.use('/api', TryCatchMiddleware(yourMiddleware({
* option1: 'value1',
* option2: 'value2'
* })));
*/
export async function yourMiddleware(
req: Request,
res: Response,
next: NextFunction,
options?: YourMiddlewareOptions
): Promise<void> {
// Middleware logic
next();
}
```
## 3. Examples
### Authentication Middleware
```typescript
/**
* Authentication middleware that validates API keys from request headers.
*
* Validates API keys against provided valid keys and sets the API key in res.locals.
* Supports single key or array of valid keys for different access levels.
*
* @example
* app.use('/api', TryCatchMiddleware(protect));
*
* app.use('/api', TryCatchMiddleware(async (req, res) => {
* await protect(req, res, 'your-secret-api-key');
* }));
*
* app.use('/api/admin', TryCatchMiddleware(async (req, res) => {
* await protect(req, res, ['admin-key-1', 'admin-key-2']);
* }));
*/
export async function protect(
req: Request,
res: Response,
validApiKeys?: string | string[]
): Promise<void> {
// Authentication logic
}
```
### Error Handling Middleware
```typescript
/**
* Error handling middleware that wraps async middleware functions with try-catch.
*
* Automatically catches errors and converts them to appropriate HTTP responses.
* Handles CustomError instances, ZodError instances, and generic errors.
*
* @example
* app.use('/api', TryCatchMiddleware(async (req, res, next) => {
* // Your middleware logic here
* next();
* }));
*
* const safeMiddleware = TryCatchMiddleware(protect);
* app.use('/api', safeMiddleware);
*/
export function TryCatchMiddleware<T = Record<string, string>>(
middlewareFn: MiddlewareFunction<T>
): MiddlewareFunction<T> {
// Error handling logic
}
```
### Protected Access Middleware
```typescript
/**
* Protected access middleware that combines authentication and error handling.
*
* Wraps route handlers with authentication and comprehensive error handling.
* Supports single API key, multiple API keys, or no validation for testing.
*
* @example
* app.get('/api/data', protectedAccessMiddleware(async (req, res) => {
* res.json({ data: 'protected data' });
* }, 'your-api-key'));
*
* app.post('/api/admin', protectedAccessMiddleware(async (req, res) => {
* res.json({ message: 'Admin operation completed' });
* }, ['admin-key-1', 'admin-key-2']));
*/
export function protectedAccessMiddleware(
handler: (req: Request, res: Response) => Promise<void>,
validApiKeys?: string | string[]
): (req: Request, res: Response, next: NextFunction) => Promise<void> {
// Protected access logic
}
```
### Middleware Types
```typescript
/**
* Configuration options for middleware components.
*
* Defines all available configuration options with their types and defaults.
* Used to provide type safety and IntelliSense for middleware configuration.
*/
export interface MiddlewareOptions {
option1?: string;
option2?: number;
option3?: boolean;
}
/**
* Type definition for middleware function signatures.
*
* Ensures consistent middleware function signatures across the package.
* Used for type safety and middleware composition.
*/
export type MiddlewareFunction<T = Record<string, string>> = (
req: Request<T>,
res: Response,
next: NextFunction
) => Promise<void>;
```
## 4. Documentation Standards
### Middleware Function Documentation
- **Description**: What the middleware does and when to use it
- **Configuration**: Document all configuration options and their defaults
- **Usage notes**: Any important behavior or error handling requirements
- **Examples**: 2-3 examples showing common usage patterns
- **Error handling**: Document how errors are handled and what responses are sent
### Configuration Interface Documentation
- **Properties**: Document all configuration properties
- **Optional properties**: Note which properties are optional and their defaults
- **Type information**: Explain the type and purpose of each property
- **Usage examples**: Show how to use the configuration in practice
### Type Definition Documentation
- **Purpose**: What the type represents
- **Generic parameters**: Document any generic type parameters
- **Usage**: How the type is typically used in middleware
- **Constraints**: Any type constraints or requirements
## 5. Examples Guidelines
- **Basic usage**: Show typical middleware usage patterns
- **Configuration**: Demonstrate different configuration options
- **Error handling**: Show how errors are handled and what responses are sent
- **Integration**: Show how middleware works with Express.js and other middleware
- **Real-world scenarios**: Include practical examples from actual use cases
## 6. Notes
- Examples are mandatory for all middleware functions and types
- Show both middleware creation and usage patterns
- Include configuration examples where relevant
- Use consistent formatting and spacing
- Reference related middleware components and types in examples
- Always show the complete middleware signature with proper types