@catbee/utils
v2.0.0
Published
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.
Readme
@catbee/utils
🧰 Utility Modules for Node.js
A modular, production-grade utility toolkit for Node.js and TypeScript, designed for robust, scalable applications. All utilities are tree-shakable and can be imported independently.
🚀 Key Features
- Modular: Import only what you need
- TypeScript-first: Full typings and type safety
- Production-ready: Robust, well-tested utilities
- Tree-shakable: Zero bloat in your bundle
- Express-friendly: Designed for scalable server apps
📦 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();📚 Modules Overview
| Module | Description | | --------------------------------------------------------------------------- | ------------------------------------------------------- | | Express Server | Fast, secure, and scalable server setup | | Array Utilities | Advanced array manipulation | | Async Utilities | Promise helpers, concurrency, timing | | Cache Utilities | In-memory caching with TTL | | Context Store | Per-request context via AsyncLocalStorage | | Crypto Utilities | Hashing, encryption, tokens | | Date Utilities | Date/time manipulation | | Decorators Utilities | TypeScript decorators for Express | | Directory Utilities | Directory and file system helpers | | Environment Utilities | Env variable management | | Exception Utilities | HTTP and error handling | | File System Utilities | File operations | | HTTP Status Codes | Typed status codes | | ID Utilities | UUID and ID generation | | Logger Utilities | Structured logging with Pino | | Middleware Utilities | Express middleware collection | | Object Utilities | Deep merge, flatten, pick/omit, etc. | | Performance Utilities | Timing, memoization, memory tracking | | Request Utilities | HTTP request parameter parsing/validation | | Response Utilities | Standardized API response formatting | | Stream Utilities | Stream conversion, batching, throttling, line splitting | | String Utilities | Casing, masking, slugifying, formatting | | Type Utilities | Type checking, conversion, guards | | Types Utilities | Common TypeScript types and interfaces | | URL Utilities | URL parsing, query manipulation, normalization | | Validate Utilities | Input validation functions |
🏁 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!
📖 Documentation
📜 License
MIT © Catbee Technologies (see the LICENSE file for the full text)
