Volodymyr Zh
Volodymyr Zh

Reputation: 347

How to use a custom middleware with nestjs-telegraf?

I am trying to implement custom Telegraf middleware with nestjs-telegraf library and connection to DB using Prisma. My AppModule is:

@Module({
  imports: [
    TelegrafModule.forRootAsync({
      imports: [ConfigModule, LoggerModule],
      useFactory: (configService: ConfigService, logger: LoggerMiddleware) => {    
        return {
          token: configService.get<string>("TELEGRAM_TOKEN")!,
          middlewares: [sessionMiddleware, logger.use]
        };
      },
      inject: [ConfigService, LoggerMiddleware]
    }),
    PrismaModule
  ],
  controllers: [],
  providers: [...someProviders]
})
export class AppModule {} 

LoggerMiddleware:

@Injectable()
export class LoggerMiddleware {
  constructor(private readonly prisma: PrismaService) {}

  async use(ctx: Context, next: NextFunction) {
    const listUser = await this.prisma.user.findMany()
    console.log('listUser = ', listUser)
    next()
  }
}

LoggerModule:

@Module({
  imports: [PrismaModule],
  providers: [LoggerMiddleware, PrismaService],
  exports: [LoggerMiddleware]
})
export class LoggerModule {}

It starts without errors and code reaches my logger middleware but then I am getting an error:

TypeError: Cannot read properties of undefined (reading 'prisma')

I have access to Prisma service from another provider and a connection to DB works. At the start, nest initializes all dependencies successfully but I don't understand why during execution it fell with this error. What did I do wrong?

Upvotes: 0

Views: 1802

Answers (1)

Volodymyr Zh
Volodymyr Zh

Reputation: 347

The answer was given by Alexander Bukhalo on github

Upvotes: 0

Related Questions