@catbee/utils
Version:
A modular, production-grade utility toolkit for Node.js and TypeScript, designed for robust, scalable applications (including Express-based services). All utilities are tree-shakable and can be imported independently.
128 lines (124 loc) • 5.21 kB
TypeScript
/*
* The MIT License
*
* Copyright (c) 2026 Catbee Technologies. https://catbee.in/license
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { Request, Response, NextFunction } from 'express';
type Middleware = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;
/**
* Attaches a unique request ID to each request.
* Useful for request tracing and correlation between logs.
*
* @param {object} [options] - Configuration options
* @param {string} [options.headerName='X-Request-ID'] - Header name for request ID
* @param {boolean} [options.exposeHeader=true] - Whether to expose the header in response
* @param {() => string} [options.generator] - Custom ID generator function
* @returns {Middleware} Express-compatible middleware
*/
declare function requestId(options?: {
headerName?: string;
exposeHeader?: boolean;
generator?: () => string;
}): Middleware;
/**
* Measures request processing time and logs or adds it to response headers.
*
* @param {object} [options] - Configuration options
* @param {boolean} [options.addHeader=true] - Whether to add X-Response-Time header
* @param {boolean} [options.logOnComplete=false] - Whether to log timing info
* @returns {Middleware} Express-compatible middleware
*/
declare function responseTime(options?: {
addHeader?: boolean;
logOnComplete?: boolean;
}): (req: Request, res: Response, next: NextFunction) => void;
/**
* Request timeout middleware.
* Aborts requests that take too long to process.
*
* @param {number} [timeoutMs=30000] - Timeout in milliseconds
* @returns {Middleware} Express-compatible middleware
*/
declare function timeout(timeoutMs?: number): Middleware;
/**
* Creates an Express middleware that initializes a per-request context.
*
* @param {object} [options] - Optional configuration
* @param {string} [options.headerName='x-request-id'] - Header to look for request ID
* @param {boolean} [options.autoLog=true] - Whether to log automatically when context is initialized
* @returns {(req: Request, res: Response, next: NextFunction) => void} Express middleware function
*/
declare function setupRequestContext(options?: {
headerName?: string;
autoLog?: boolean;
}): Middleware;
interface ErrorHandlerOptions {
/** Whether to log errors (default: true) */
logErrors?: boolean;
/** Whether to include error details in non-production (default: false) */
includeDetails?: boolean;
}
/**
* Global error handling middleware with enhanced features.
*
* @param {ErrorHandlerOptions} options - Error handler options
* @param {boolean} [options.logErrors=true] - Whether to log errors
* @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production
* @returns Error middleware
*
* @example
* import express from 'express';
* import { errorHandler } from '@catbee/utils';
*
* const app = express();
*
* // Your routes
* app.get('/ping', (req, res) => {
* throw new Error('Something went wrong');
* });
*
* // Error handler (must be last middleware)
* app.use(errorHandler({ includeDetails: true }));
*
* app.listen(3000, () => {
* console.log('Server running on port 3000');
* });
*/
declare function errorHandler(options?: ErrorHandlerOptions): (err: any, req: Request, res: Response, _next: NextFunction) => Response<any, Record<string, any>>;
/**
* Health check middleware for service status and custom checks.
*
* @param {object} [options] - Health check options
* @param {string} [options.path='/healthz'] - Health check endpoint path
* @param {Array<{name: string; check: () => Promise<boolean> | boolean}>} [options.checks] - Custom health checks
* @param {boolean} [options.detailed=true] - Show detailed check results
* @returns {Middleware} Express-compatible middleware
*/
declare function healthCheck(options?: {
path?: string;
checks?: Array<{
name: string;
check: () => Promise<boolean> | boolean;
}>;
detailed?: boolean;
}): Middleware;
export { errorHandler, healthCheck, requestId, responseTime, setupRequestContext, timeout };
export type { ErrorHandlerOptions, Middleware };