nestjs / nest

A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript 🚀
https://nestjs.com
MIT License
67.77k stars 7.64k forks source link

TypeError: stream.on is not a function on microservice bootup. #7269

Closed mahmadmujtaba2 closed 3 years ago

mahmadmujtaba2 commented 3 years ago

Bug Report

Current behavior

Running a simple microservice using NATS. Following example on offical docs. Fails on bootup. Errors are.

(node:22611) UnhandledPromiseRejectionWarning: TypeError: stream.on is not a function
    at ServerNats.handleError (/home/ahmad/Workspace/VsCode/SptsNest/node_modules/@nestjs/microservices/server/server-nats.js:85:16)
    at ServerNats.listen (/home/ahmad/Workspace/VsCode/SptsNest/node_modules/@nestjs/microservices/server/server-nats.js:22:14)
    at /home/ahmad/Workspace/VsCode/SptsNest/node_modules/@nestjs/microservices/nest-microservice.js:86:51
    at new Promise (<anonymous>)
    at NestMicroservice.listenAsync (/home/ahmad/Workspace/VsCode/SptsNest/node_modules/@nestjs/microservices/nest-microservice.js:86:16)
    at NestMicroservice.listen (/home/ahmad/Workspace/VsCode/SptsNest/node_modules/@nestjs/microservices/nest-microservice.js:81:14)
    at /home/ahmad/Workspace/VsCode/SptsNest/node_modules/@nestjs/core/nest-application.js:241:32
    at new Promise (<anonymous>)
    at listenToPromise (/home/ahmad/Workspace/VsCode/SptsNest/node_modules/@nestjs/core/nest-application.js:240:16)
    at Array.map (<anonymous>)
    at NestApplication.startAllMicroservices (/home/ahmad/Workspace/VsCode/SptsNest/node_modules/@nestjs/core/nest-application.js:133:40)
    at /home/ahmad/Workspace/VsCode/SptsNest/node_modules/@nestjs/core/nest-application.js:137:44
    at new Promise (<anonymous>)
    at NestApplication.startAllMicroservicesAsync (/home/ahmad/Workspace/VsCode/SptsNest/node_modules/@nestjs/core/nest-application.js:137:16)
    at /home/ahmad/Workspace/VsCode/SptsNest/node_modules/@nestjs/core/nest-factory.js:127:40
    at Function.run (/home/ahmad/Workspace/VsCode/SptsNest/node_modules/@nestjs/core/errors/exceptions-zone.js:9:13)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:22611) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:22611) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Input Code

// main.ts
import { NestFactory } from '@nestjs/core';
import { MicroserviceOptions, Transport } from '@nestjs/microservices';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.connectMicroservice<MicroserviceOptions>({
    transport: Transport.NATS,
    options: {
      url: 'nats://localhost:4222',
      timeout: 1000,
    },
  });
  await app.startAllMicroservicesAsync();
  await app.listen(8800);
}
bootstrap();
// controller.ts
import { Controller, Get, Inject } from '@nestjs/common';
import {
  ClientProxy,
  Ctx,
  EventPattern,
  NatsContext,
  Payload,
} from '@nestjs/microservices';
import { PieceProgress } from './schemas/piece-progress.schema';
import { PieceProgressService } from './piece-progress.service';
import { Observable } from 'rxjs';

@Controller('piece-progress')
export class PieceProgressController {
  constructor(
    private readonly pieceProgressService: PieceProgressService,
    @Inject('NATS_SERVICE')
    private readonly natsClient: ClientProxy,
  ) {}

  @Get()
  async findAll(): Promise<PieceProgress[]> {
    return this.pieceProgressService.findAll();
  }

  @EventPattern('get-running-orders')
  async GetRunningOrders(
    @Payload() pieceIds: number[],
    @Ctx() context: NatsContext,
  ): Promise<Observable<any>> {
    console.log(`PieceIds are: ${pieceIds}`);
    console.log(`Context is: ${context}`);

    // send this data to a topic which micro-redis is subscribed,
    // such that it can save the data into its memory.
    const runningOrdersData = await this.pieceProgressService.GetRunningOrders(
      pieceIds,
    );

    // send data into another topic,
    // such that micro-redis subs to it and updates its data to latest.
    return this.natsClient.send('set-running-orders', runningOrdersData);
  }
}
module.ts
import {
  PieceProgress,
  PieceProgressSchema,
} from './schemas/piece-progress.schema';
import { Module } from '@nestjs/common';
import { PieceProgressService } from './piece-progress.service';
import { PieceProgressController } from './piece-progress.controller';
import { ClientsModule, Transport } from '@nestjs/microservices';
import { MongooseModule } from '@nestjs/mongoose';

@Module({
  imports: [
    ClientsModule.register([
      {
        name: 'NATS_SERVICE',
        transport: Transport.NATS,
        options: {
          url: 'nats://localhost:4222',
        },
      },
    ]),
    MongooseModule.forFeature([
      {
        name: PieceProgress.name,
        schema: PieceProgressSchema,
      },
    ]),
  ],
  controllers: [PieceProgressController],
  providers: [PieceProgressService],
})
export class PieceProgressModule {}
import { PieceProgress } from './schemas/piece-progress.schema';
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { PieceProgressDocument } from './schemas/piece-progress.schema';

@Injectable()
export class PieceProgressService {
  constructor(
    @InjectModel(PieceProgress.name)
    private pieceProgressModel: Model<PieceProgressDocument>,
  ) {}

  async findAll(): Promise<PieceProgress[]> {
    return this.pieceProgressModel.find().exec();
  }

  // todo: return all scannings for orders present by piece ids.
  async GetRunningOrders(PieceIds: number[]): Promise<PieceProgress[]> {
    return this.pieceProgressModel.find().exec();
  }
}

Expected behavior

Microservice to boot up without errors to be used in other project.

Environment

Nest version: 7.6.15

For Tooling issues:

Others: IDE: VsCode PackageManager: yarn

kamilmysliwiec commented 3 years ago

Use NATS 1.4, not v2.

Please, use our Discord channel (support) for such questions. We are using GitHub to track bugs, feature requests, and potential improvements.