NestJS problems with shared modules

Viewed 133

I am trying to create a shared logging module in NestJS that can be shared between multiple micro-services.

The logging module works when it is part of the micro-service but when I extract the code to its own NPM module it no longer works.

Below is a sample of my shared NPM module code:

 // my-logger.module.ts


import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { LoggerModule } from 'nestjs-pino';

@Module({
  imports: [
    LoggerModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: async (configService: ConfigService) => ({
        pinoHttp: {
          level: process.env.LOG_LEVEL || 'info',
          redact: configService.get<string[]>('logger.redacted.fields'),
          prettyPrint: {
            colorize: false,
            singleLine: true,
            levelFirst: false,
            translateTime: "yyyy-mm-dd'T'HH:MM:ss.l'Z'",
            messageFormat: '{req.headers.x-correlation-id} [{context}] {msg}',
            ignore: 'pid,hostname,context,req,res,responseTime',
            errorLikeObjectKeys: ['err', 'error'],
          },
        },
      }),
      inject: [ConfigService],
    }),
  ],
  controllers: [],
  providers: [],
})
export class MyLoggerModule {}

Below is a sample of the App Module from my NestJS micro-service

// app.module.ts

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import configuration from '../config/configuration';
import { MyLoggerModule } from '@my-company/my-logger.module';
import { HttpModule } from '@nestjs/axios';

@Module({
  imports: [
    ConfigModule.forRoot({ load: [configuration] }),
    MyLoggerModule,
    HttpModule,
  ],
  controllers: [],
  providers: [],
})
export class AppModule {}

The micro-service builds and deploys correctly with the shared npm module. However, each time I send a new request it causes the service to restart with the following error:

node[1]: ../src/tcp_wrap.cc:149:static void node::TCPWrap::New(const v8::FunctionCallbackInfo<v8::Value>&): Assertion `args[0]->IsInt32()' failed.

Does anyone have any ideas on why this is failing ?

Note: I am guessing it has something to do with the ConfigService/ConfigModule being used in both modules. However, I don't understand why the same code works when it is part of the micro-service

1 Answers

We experienced similar issues trying to configure shared modules and ran into a whole host of issues. The root cause was the package versions and that these were not aligned. This answer pointed me in the right direction.

In summary, double check all package version numbers across both applications and shared packages.

Related