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 🙏

© 2024 – Pkg Stats / Ryan Hefner

@gedai/nestjs-common

v0.0.10

Published

Common components for gedai project

Downloads

11

Readme

Description

This package serves as a fundamental configuration utility for NestJS services, providing essential settings and dependencies to streamline development processes. It relies on @gedai/nestjs-core as a key dependency for keeping track of contexts. To ensure smooth operation, it's imperative to install and configure this dependency to ensure smooth operation.

Getting Started

Step 1: Installation

Install the necessary packages with your favorite Package Manager.

$ npm install @gedai/nestjs-core

Step 2: Configuration Setup

In your app.module.ts file, import the required modules and configure them:

// app.module.ts
import { CommonConfigModule } from '@gedai/nestjs-common';
import { ContextModule } from '@gedai/nestjs-core';
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
  imports: [
    // Set up Context Module
    ContextModule.forRoot({}),
    // Set up Common Module to provide configuration
    CommonConfigModule.forRoot({
      appName: 'gedai-app',
      environment: 'development',
      logger: {
        level: 'debug',
        format: 'pretty',
        obfuscation: { sensitiveKeys: ['cardnumber'] },
      },
      httpTrafficInspection: {
        ignoredInboundRoutes: ['/v1/hidden-paths/*', '/v1/health'],
        allowedOutboundRoutes: ['/v1/inpected-outbound-routes/*'],
      },
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Step 3: Application Wide Configuration

In your main.ts file, configure the application with the unified configuration handler:

// main.ts using the unified handler
import { createNestApp } from '@gedai/nestjs-common';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await createNestApp(AppModule);
  await app.listen(3000);
}
bootstrap();

Or, if you prefer, manually setting various common settings:

// main.ts manually
import { configureContextWrappers } from '@gedai/nestjs-core';
import {
  configureCORS,
  configureCompression,
  configureExceptionHandler,
  configureHelmet,
  configureHttpInspectorInbound,
  configureHttpInspectorOutbound,
  configureLogger,
  configureRoutePrefix,
  configureValidation,
  configureVersioning,
} from '@gedai/nestjs-common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule, { bufferLogs: true })
    // Configure Context Wrappers
    .then(configureContextWrappers)
    // Configure Logger
    .then(configureLogger)
    // Configure Exception Handler
    .then(configureExceptionHandler)
    // Configure Traffic Inspection
    .then(configureHttpInspectorInbound)
    .then(configureHttpInspectorOutbound)
    // Other Common Configuration
    .then(configureCORS)
    .then(configureHelmet)
    .then(configureCompression)
    .then(configureValidation)
    .then(configureVersioning)
    .then(configureRoutePrefix);

  await app.listen(3000);
}
bootstrap();

Step 4: Integration and Usage

With the setup complete, utilize Nest's default logger anywhere in your application.

// app.service.ts
import { ContextService } from '@gedai/nestjs-core';
import { Injectable, Logger } from '@nestjs/common';

@Injectable()
export class AppService {
  private logger = new Logger(this.constructor.name);

  getHello(): string {
    this.logger.log('Hello, Jack!');
    return 'Hello, Jack!';
  }
}

Logger Interface and Error Handling

The logger is configured to seamlessly detect and parse error objects, simplifying the process of handling exceptions within your codebase. When an exception occurs and you need to manage it manually, you can effortlessly pass the error object down to the logger for efficient tracking and debugging. Additionally, the logger gracefully handles unhandled exceptions, ensuring comprehensive error monitoring throughout your application.

try {
  throw new Error('Too Bad 💣');
}
catch(error) {
  this.logger.error({ message: 'Something bad happend here!', error: });
}

Extra Configuration

Settings can be configured by passing configuration objects to CommonConfigModule

Obfuscating Logs

This library comes equipped with a built-in obfuscator designed to obfuscate any sensitive keys detected in logs automatically. Should you require additional keys to be obfuscated, or if you prefer to implement a custom obfuscator, you can easily extend the functionality by providing your own obfuscator or keys to the CommonConfigModule.

By leveraging this feature, you can safeguard sensitive information within your logs, ensuring compliance with privacy regulations and bolstering the security of your application's logging system.

Ignoring Routes from Inspection

Configuring specific routes to be excluded from inspection is particularly useful for health checks or heavy endpoints. Wildcards are supported in the configurations, allowing for flexible route matching.

Wildcard usage:

  • * matches any number of tokens in the request.path

Examples:

  • /v1/accounts/\*/holder
    • Hides routes like /v1/accounts/:id/holder from inspection.
  • /v1/accounts/\*
    • Conceals nested routes within /v1/accounts from inspection.

Available Features

  • Logging
  • Anonymized keys on logged objects
  • Inbound HTTP traffic inspection
  • Outbound HTTP traffic inspection
  • Compression
  • Helmet
  • Validation
  • CORS
  • API Versioning
  • Route Prefixing
  • Logged Metadata in logs

License

Gedai is MIT licensed.