2.1.2 • Published 7 months ago

@empe/base-app v2.1.2

Weekly downloads
-
License
MIT
Repository
github
Last release
7 months ago

@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-app

Features

  • 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

2.1.2

7 months ago

2.1.1

7 months ago

2.1.0

8 months ago

2.0.2

10 months ago

2.0.1

10 months ago

2.0.0

11 months ago

1.5.0

11 months ago

1.4.1

11 months ago

1.4.0

11 months ago

1.3.2

11 months ago

1.3.1

11 months ago

1.3.0

11 months ago

1.2.1

11 months ago

1.2.0

11 months ago

1.1.0

11 months ago

1.0.2

12 months ago

1.0.1

12 months ago

1.0.0

12 months ago

0.0.3

12 months ago

0.0.2

12 months ago

0.0.1

12 months ago