Introduction
@catbee/utils – The Ultimate Utility Toolkit for Node.js & TypeScript
A modular, production-grade utility library for Node.js and TypeScript, built for robust, scalable applications and enterprise Express services. Every utility is tree-shakable, fully typed, and can be imported independently for optimal bundle size.
🚀 Features
- Type-safe: All utilities are fully typed for maximum safety and IDE support.
- Tree-shakable: Import only what you need—no bloat, no dead code.
- Production-ready: Designed for high-performance, scalable Node.js apps.
- Express-friendly: Includes context, middleware, decorators, and server helpers.
- Comprehensive: Covers arrays, objects, strings, streams, requests, responses, performance, caching, validation, and more.
- Configurable: Global config system with environment variable support.
- Minimal dependencies: Minimal footprint, maximum reliability.
📦 Installation
npm i @catbee/utils
⚡ Quick Start
import { ServerConfigBuilder, ExpressServer } from '@catbee/utils/server';
import { Router } from 'express';
const config = new ServerConfigBuilder()
.withPort(3000)
.withCors({ origin: '*' })
.enableRateLimit({ max: 50, windowMs: 60000 })
.enableRequestLogging({ ignorePaths: ['/healthz', '/metrics'] })
.withHealthCheck({ path: '/health', detailed: true })
.enableOpenApi('./openapi.yaml', { mountPath: '/docs' })
.withGlobalHeaders({ 'X-Powered-By': 'Catbee' })
.withGlobalPrefix('/api')
.withRequestId({ headerName: 'X-Request-Id', exposeHeader: true })
.enableResponseTime({ addHeader: true, logOnComplete: true })
.build();
const server = new ExpressServer(config, {
beforeInit: srv => console.log('Initializing server...'),
afterInit: srv => console.log('Server initialized'),
beforeStart: app => console.log('Starting server...'),
afterStart: srv => console.log('Server started!'),
beforeStop: srv => console.log('Stopping server...'),
afterStop: () => console.log('Server stopped.'),
onRequest: (req, res, next) => {
console.log('Processing request:', req.method, req.url);
next();
},
onResponse: (req, res, next) => {
res.setHeader('X-Processed-By', 'ExpressServer');
next();
},
onError: (err, req, res, next) => {
console.error('Custom error handler:', err);
res.status(500).json({ error: 'Custom error: ' + err.message });
}
});
// Register routes
const router = server.createRouter('/users');
router.get('/', (req, res) => res.json({ users: [] }));
router.post('/', (req, res) => res.json({ created: true }));
// Or set a base router for all routes
const baseRouter = Router();
baseRouter.use('/users', router);
server.setBaseRouter(baseRouter);
server.registerHealthCheck('database', async () => await checkDatabaseConnection());
server.useMiddleware(loggingMiddleware, errorMiddleware);
await server.start();
server.enableGracefulShutdown();
🏁 Usage
This library supports flexible import patterns to suit your needs:
Root-level imports (everything available)
Import any utility directly from the root package:
import { chunk, sleep, TTLCache, getLogger, ServerConfigBuilder } from '@catbee/utils';
Module-level imports (scoped imports)
Import only from specific modules for better organization and smaller bundles:
// Import only server-related exports
import { ServerConfigBuilder, ExpressServer } from '@catbee/utils/server';
// Import only date utilities
import { formatDate, addDays, DateBuilder } from '@catbee/utils/date';
// Import only crypto utilities
import { hashPassword, verifyPassword } from '@catbee/utils/crypto';
Both import styles are fully supported and tree-shakable. Use whichever fits your project structure best!
⚙️ Configuration
Global configuration management with environment variable support:
- Config – Centralized runtime configuration
🏢 Express Server
Enterprise-grade Express server utilities:
- Express Server – Fast, secure, and scalable server setup
🧩 Utility Modules
Explore the full suite of utilities, each with detailed API docs and examples:
- Array – Advanced array manipulation
- Async – Promise helpers, concurrency, timing
- Cache – In-memory caching with TTL
- Context Store – Per-request context via AsyncLocalStorage
- Crypto – Hashing, encryption, tokens
- Date – Date/time manipulation
- Decorator – TypeScript decorators for Express
- Directory – Directory and file system helpers
- Environment – Env variable management
- Exception – HTTP and error handling
- File System – File operations
- HTTP Status Codes – Typed status codes
- ID – UUID and ID generation
- Logger – Structured logging with Pino
- Middleware – Express middleware collection
- Object – Deep merge, flatten, pick/omit, etc.
- Performance – Timing, memoization, memory tracking
- Request – HTTP request parameter parsing/validation
- Response – Standardized API response formatting
- Stream – Stream conversion, batching, throttling, line splitting
- String – Casing, masking, slugifying, formatting
- Type – Type checking, conversion, guards
- Types – Common TypeScript types and interfaces
- URL – URL parsing, query manipulation, normalization
- Validation – Input validation functions
📜 License
MIT © Catbee Technologies (see the LICENSE file for the full text)