npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@develop-x/nest-core

v1.0.48

Published

## Overview

Downloads

103

Readme

@develop-x/nest-core

Overview

@develop-x/nest-core is a comprehensive NestJS module that integrates essential microservice functionalities including logging, exception handling, response formatting, internationalization, tracing, service connectivity, authentication context, and Consul service discovery.

Installation

npm install @develop-x/nest-core

Features

  • Unified Integration: Single module that combines all essential microservice components
  • Logging Module: High-performance structured logging with OpenTelemetry integration
  • Exception Handling: Centralized exception handling with consistent error responses
  • Response Formatting: Standardized API response structure
  • Internationalization: Multi-language support with automatic language detection
  • Distributed Tracing: OpenTelemetry integration for request tracing
  • Service Discovery: Consul integration for microservice communication
  • Service Connector: HTTP client with circuit breaker and service discovery
  • Authentication Context: User context management across requests
  • Internal Authentication: API key-based internal service authentication
  • Configuration Management: Centralized configuration with environment support

Usage

Basic Setup

Import the CoreModule in your application's main module:

import { Module } from '@nestjs/common';
import { CoreModule } from '@develop-x/nest-core';

@Module({
  imports: [
    CoreModule.forRoot({
      serviceName: 'user-service',
      loggerLevel: 'info',
      fallbackLanguage: 'en',
      
      // Optional features
      enableConsul: true,
      consulUrl: 'http://consul:8500',
      
      enableServiceConnector: true,
      apiKey: 'your-internal-api-key',
      
      enableAuthContext: true,
      enableInternalAuth: true,
    }),
  ],
})
export class AppModule {}

Advanced Configuration

import { Module } from '@nestjs/common';
import { CoreModule } from '@develop-x/nest-core';

@Module({
  imports: [
    CoreModule.forRoot({
      // Required
      serviceName: 'order-service',
      
      // Environment configuration
      envFilePath: '.env.production',
      configLoaders: [
        () => ({
          database: {
            host: process.env.DB_HOST,
            port: parseInt(process.env.DB_PORT),
          },
        }),
      ],
      
      // Logging configuration
      loggerLevel: 'debug',
      
      // Internationalization
      fallbackLanguage: 'en',
      i18nPath: './locales',
      
      // Service discovery and connectivity
      enableConsul: true,
      consulUrl: 'http://consul:8500',
      
      enableServiceConnector: true,
      apiKey: process.env.INTERNAL_API_KEY,
      breakerOptions: {
        timeout: 5000,
        errorThresholdPercentage: 50,
        resetTimeout: 30000,
      },
      
      // Authentication
      enableAuthContext: true,
      enableInternalAuth: true,
    }),
  ],
})
export class AppModule {}

Configuration Options

CoreModuleOptions

interface CoreModuleOptions {
  // Required
  serviceName: string;                    // Service name for logging and tracing
  
  // Environment and Configuration
  envFilePath?: string;                   // Path to environment file (default: '.env')
  configLoaders?: (() => any)[];          // Custom configuration loaders
  
  // Logging
  loggerLevel?: 'debug' | 'info' | 'warn' | 'error'; // Log level (default: 'info')
  
  // Internationalization
  fallbackLanguage?: string;              // Fallback language (default: 'en')
  i18nPath?: string;                      // Path to i18n files (default: './i18n')
  
  // Service Discovery
  enableConsul?: boolean;                 // Enable Consul integration
  consulUrl?: string;                     // Consul server URL
  
  // Service Connectivity
  enableServiceConnector?: boolean;       // Enable HTTP client with circuit breaker
  apiKey?: string;                        // API key for internal authentication
  breakerOptions?: CircuitBreakerOptions; // Circuit breaker configuration
  
  // Authentication
  enableAuthContext?: boolean;            // Enable user context middleware
  enableInternalAuth?: boolean;           // Enable internal API authentication
}

Included Modules

1. Logger Module

Provides structured logging with OpenTelemetry integration:

import { Injectable } from '@nestjs/common';
import { LoggerService } from '@develop-x/nest-logger';

@Injectable()
export class UserService {
  constructor(private readonly logger: LoggerService) {}

  async createUser(userData: any) {
    this.logger.info('Creating user', { userId: userData.id });
    // ... implementation
  }
}

2. Response Module

Standardizes API responses:

import { Injectable } from '@nestjs/common';
import { ResponseHelper } from '@develop-x/nest-response';

@Injectable()
export class UserController {
  constructor(private readonly responseHelper: ResponseHelper) {}

  @Get(':id')
  async getUser(@Param('id') id: string) {
    const user = await this.userService.findById(id);
    return this.responseHelper.success(user, 'User retrieved successfully');
  }
}

3. Exception Module

Centralized exception handling:

import { Injectable } from '@nestjs/common';
import { BusinessException } from '@develop-x/nest-exception';

@Injectable()
export class UserService {
  async findUser(id: string) {
    const user = await this.userRepository.findById(id);
    if (!user) {
      throw new BusinessException(1001, { userId: id }, 404, 'User not found');
    }
    return user;
  }
}

4. Service Connector

HTTP client with service discovery and circuit breaker:

import { Injectable } from '@nestjs/common';
import { HttpClientService } from '@develop-x/nest-service-connector';

@Injectable()
export class OrderService {
  constructor(private readonly httpClient: HttpClientService) {}

  async getUserOrders(userId: string) {
    return this.httpClient
      .createRequest('user-service')
      .setPath(`/users/${userId}/orders`)
      .get<Order[]>();
  }
}

5. Authentication Context

User context management:

import { Controller, Get } from '@nestjs/common';
import { CurrentUser, CurrentUserId } from '@develop-x/nest-auth-context';

@Controller('profile')
export class ProfileController {
  @Get()
  getProfile(@CurrentUser() user: any, @CurrentUserId() userId: string) {
    return { user, userId };
  }
}

6. Internationalization

Multi-language support:

import { Injectable } from '@nestjs/common';
import { I18nService } from 'nestjs-i18n';

@Injectable()
export class MessageService {
  constructor(private readonly i18n: I18nService) {}

  getWelcomeMessage(lang: string) {
    return this.i18n.translate('messages.welcome', { lang });
  }
}

Environment Configuration

Development Environment

// .env.development
NODE_ENV=development
SERVICE_NAME=user-service
LOG_LEVEL=debug
CONSUL_URL=http://localhost:8500
INTERNAL_API_KEY=dev-api-key-123

Production Environment

// .env.production
NODE_ENV=production
SERVICE_NAME=user-service
LOG_LEVEL=info
CONSUL_URL=http://consul:8500
INTERNAL_API_KEY=prod-secure-api-key

Integration Examples

Complete Microservice Setup

import { Module } from '@nestjs/common';
import { CoreModule } from '@develop-x/nest-core';
import { UsersModule } from './users/users.module';
import { OrdersModule } from './orders/orders.module';

@Module({
  imports: [
    CoreModule.forRoot({
      serviceName: 'api-gateway',
      loggerLevel: process.env.NODE_ENV === 'production' ? 'info' : 'debug',
      
      // Enable all features for a complete setup
      enableConsul: true,
      consulUrl: process.env.CONSUL_URL,
      
      enableServiceConnector: true,
      apiKey: process.env.INTERNAL_API_KEY,
      breakerOptions: {
        timeout: 10000,
        errorThresholdPercentage: 60,
        resetTimeout: 30000,
      },
      
      enableAuthContext: true,
      enableInternalAuth: true,
      
      // Internationalization
      fallbackLanguage: 'en',
      i18nPath: './src/i18n',
    }),
    
    // Your application modules
    UsersModule,
    OrdersModule,
  ],
})
export class AppModule {}

Health Check Integration

import { Controller, Get } from '@nestjs/common';
import { ResponseHelper } from '@develop-x/nest-response';

@Controller('health')
export class HealthController {
  constructor(private readonly responseHelper: ResponseHelper) {}

  @Get()
  getHealth() {
    return this.responseHelper.success(
      {
        status: 'healthy',
        timestamp: new Date().toISOString(),
        uptime: process.uptime(),
        version: process.env.npm_package_version,
      },
      'Service is healthy'
    );
  }
}

Error Handling Setup

import { Module } from '@nestjs/common';
import { APP_FILTER } from '@nestjs/core';
import { BaseGlobalExceptionFilter } from '@develop-x/nest-exception';

@Module({
  providers: [
    {
      provide: APP_FILTER,
      useClass: BaseGlobalExceptionFilter,
    },
  ],
})
export class AppModule {}

Docker Integration

Dockerfile

FROM node:18-alpine

WORKDIR /app

COPY package*.json ./
RUN npm ci --only=production

COPY . .
RUN npm run build

EXPOSE 3000

CMD ["node", "dist/main"]

Docker Compose

version: '3.8'
services:
  consul:
    image: consul:latest
    ports:
      - "8500:8500"
    command: consul agent -dev -client=0.0.0.0

  user-service:
    build: .
    environment:
      - NODE_ENV=production
      - SERVICE_NAME=user-service
      - CONSUL_URL=http://consul:8500
      - INTERNAL_API_KEY=secure-api-key
    depends_on:
      - consul
    ports:
      - "3000:3000"

Testing

Unit Testing

import { Test, TestingModule } from '@nestjs/testing';
import { CoreModule } from '@develop-x/nest-core';
import { UserService } from './user.service';

describe('UserService', () => {
  let service: UserService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      imports: [
        CoreModule.forRoot({
          serviceName: 'test-service',
          loggerLevel: 'error', // Reduce noise in tests
          enableConsul: false,  // Disable external dependencies
          enableServiceConnector: false,
        }),
      ],
      providers: [UserService],
    }).compile();

    service = module.get<UserService>(UserService);
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });
});

Integration Testing

import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import { CoreModule } from '@develop-x/nest-core';
import * as request from 'supertest';

describe('App (e2e)', () => {
  let app: INestApplication;

  beforeEach(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [
        CoreModule.forRoot({
          serviceName: 'test-app',
          enableConsul: false,
          enableServiceConnector: false,
        }),
      ],
    }).compile();

    app = moduleFixture.createNestApplication();
    await app.init();
  });

  it('/health (GET)', () => {
    return request(app.getHttpServer())
      .get('/health')
      .expect(200)
      .expect((res) => {
        expect(res.body.code).toBe(200);
        expect(res.body.data.status).toBe('healthy');
      });
  });
});

Best Practices

  1. Service Naming: Use consistent and descriptive service names
  2. Environment Configuration: Use environment variables for different deployments
  3. Logging: Implement structured logging with appropriate log levels
  4. Error Handling: Use business exceptions for domain-specific errors
  5. Service Discovery: Register services with health checks
  6. Circuit Breakers: Configure appropriate thresholds for external calls
  7. Authentication: Secure internal service communication
  8. Monitoring: Implement comprehensive health checks and metrics

Performance Considerations

  1. Logging: Use appropriate log levels to avoid performance impact
  2. Circuit Breakers: Configure timeouts based on your SLA requirements
  3. Service Discovery: Cache service discovery results when appropriate
  4. Connection Pooling: HTTP client automatically pools connections
  5. Async Operations: Use async/await for all I/O operations

Troubleshooting

Common Issues

  1. Service Registration Failures: Check Consul connectivity and configuration
  2. Circuit Breaker Open: Verify target service health and adjust thresholds
  3. Authentication Failures: Ensure API keys are correctly configured
  4. Logging Issues: Check log level configuration and output destinations

Debug Mode

Enable debug logging for troubleshooting:

CoreModule.forRoot({
  serviceName: 'debug-service',
  loggerLevel: 'debug',
  // ... other options
})

Migration Guide

From Individual Packages

If you're currently using individual packages, you can migrate to the core module:

// Before
import { LoggerModule } from '@develop-x/nest-logger';
import { ResponseModule } from '@develop-x/nest-response';
import { ConsulModule } from '@develop-x/nest-consul';

// After
import { CoreModule } from '@develop-x/nest-core';

@Module({
  imports: [
    CoreModule.forRoot({
      serviceName: 'my-service',
      enableConsul: true,
      // ... other options
    }),
  ],
})
export class AppModule {}

Dependencies

This package includes and configures the following dependencies:

  • @develop-x/nest-logger: Structured logging
  • @develop-x/nest-response: Response formatting
  • @develop-x/nest-exception: Exception handling
  • @develop-x/nest-auth-context: Authentication context
  • @develop-x/nest-internal-auth: Internal authentication
  • @develop-x/nest-service-connector: HTTP client with circuit breaker
  • @develop-x/nest-consul: Consul integration
  • @nestjs/config: Configuration management
  • nestjs-i18n: Internationalization

License

ISC

Support

For issues and questions, please refer to the project repository or contact the development team.