@empe/base-app v2.1.2
@empe/base-app
A foundation package providing common utilities, error handling, middleware, and environment management for Empe applications. This package standardizes core functionality across services in the Empe ecosystem.
Installation
npm install @empe/base-app
# or
yarn add @empe/base-appFeatures
- Environment Management: Utilities for accessing and validating environment variables
- Error Handling: Standardized error classes and middleware
- Request Validation: Middleware for validating request parameters using Joi
- Logging: Integration with @empe/logger for consistent logging
- Rate Limiting: Configurable rate limiting for API endpoints
- Async Handling: Utilities for handling async Express routes
Usage
Environment Management
import { getHost, getPort, getNodeEnv } from '@empe/base-app/tools';
// Get environment variables with validation
const host = getHost(); // e.g., 'https://example.com'
const port = getPort(); // e.g., 3000
const nodeEnv = getNodeEnv(); // 'development', 'production', or 'test'Logging
The base-app package provides a convenient wrapper around the @empe/logger package. The actual logger implementation is in the @empe/logger package, while base-app only provides a simplified createLogger function that injects environment variables:
// Implementation in base-app/tools/logger.ts
export const createLogger = (name: string) => createLoggerInstance(name, getNodeEnv(), getLogLevel(), getLogsDir());This makes it easy to create a properly configured logger without manually handling environment variables:
import { createLogger } from '@empe/base-app/tools';
// Create a logger for your service
const logger = createLogger('MyService');
logger.info('Service starting');
logger.debug('Debug information', { userId: 123 });
logger.error('Error occurred', { error: new Error('Something went wrong') });The logger automatically uses the appropriate environment variables (NODE_ENV, LOG_LEVEL, LOG_DIR) and applies consistent formatting across all services.
Error Handling
import { errorMiddleware } from '@empe/base-app/middlewares';
import { InvalidRequestError } from '@empe/base-app/errors';
import { createLogger } from '@empe/base-app/tools';
const logger = createLogger('MyService');
const app = express();
// Add routes
app.get('/resource/:id', (req, res) => {
const { id } = req.params;
if (!id) {
throw new InvalidRequestError('ID is required');
}
// Process request
});
// Add error handling middleware
app.use(errorMiddleware(logger));Request Validation
import { validateRequest } from '@empe/base-app/middlewares';
import Joi from 'joi';
const userSchema = Joi.object({
name: Joi.string().required(),
email: Joi.string().email().required(),
age: Joi.number().integer().min(18).required(),
});
app.post('/users', validateRequest({ body: userSchema }), (req, res) => {
// Request body is validated and typed
const user = req.body;
// Process user
res.status(201).json(user);
});Async Route Handling
import { asyncHandler } from '@empe/base-app/tools';
app.get(
'/users/:id',
asyncHandler(async (req, res) => {
const user = await userService.findById(req.params.id);
res.json(user);
// No need for try/catch - errors are automatically passed to error middleware
})
);Rate Limiting
import { globalRateLimiter } from '@empe/base-app/middlewares';
// Apply rate limiting to all routes
app.use(globalRateLimiter);
// Or apply to specific routes
app.post('/login', globalRateLimiter, loginHandler);Exports
The package provides the following export paths:
@empe/base-app/tools- Environment utilities, logger, and async handlers@empe/base-app/errors- Error classes for different types of application errors@empe/base-app/middlewares- Express middleware for validation, error handling, and rate limiting@empe/base-app/schemas- Common Joi schemas for validation
License
MIT
7 months ago
7 months ago
8 months ago
10 months ago
10 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
12 months ago
12 months ago
12 months ago
12 months ago
12 months ago
12 months ago