Nestjs middleware with dependencies - node.js

I am having trouble creating a middleware that has two dependencies (TypeORModule.forFeature([USER]), FirebaseModule).
What I have done is create an AuthModule which looks like this:
#Module({
imports: [
FirebaseModule,
TypeOrmModule.forFeature([User])
],
providers: [
AuthMiddleware
],
})
and the middleware which looks like this
export class AuthMiddleware implements NestMiddleware {
constructor(
#InjectRepository(User)
private usersRepository: Repository<User>,
private firebaseService: FirebaseService
) {}
async use(req: Request, res: Response, next: () => void) {...}
}
and my app module which looks like this
#Module({
imports: [
TypeOrmModule.forRoot({
...config.get("database"),
entities: [__dirname + '/entities/**/*.{js,ts}']
}),
AuthModule,
exampleModule
],
providers: [
AuthMiddleware
]
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer): any {
consumer.apply(AuthMiddleware).forRoutes("*")
}
}
I get many errors and I try to shift things around to make it work but I simply can't get it to happen. I get errors from
Please make sure that the argument UserRepository at index [0] is available in the module(sometimes AppModule, sometimes exampleModule) context.
Do other modules (controller ones, as in providing api services) need to also import the middleware module if it applies to them too?
In general, how do I go on about implementing middlewares that depend on external modules? Do they have to be modules so I can import the requires modules?
I'd love some help, thanks!

You shiouldn't need to re-add AuthMiddleware to the AppModule's providers. It already exists in AuthModule. Also, you can bind the middleware inside the AuthModule if you want instead of in the AppModule and it will have the same global scope.

Related

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?
The answer was given by Alexander Bukhalo on github

Nest can't resolve DataSource as dependency in my custom module

I've had a problem with dependencies in NestJS. On launch my NestJS app, compiler throw me this:
Nest can't resolve dependencies of the OtpRepository (?). Please make sure that the argument DataSource at index [0] is available in the TypeOrmModule context.
OtpModule.ts
#Global()
#Module({
imports: [TypeOrmModule.forFeature([Otp])],
providers: [
OtpService,
OtpRepository,
],
exports: [TypeOrmModule, OtpService, OtpRepository],
})
export class OtpModule {}
OtpService.ts
#Injectable()
export class OtpService {
constructor(private readonly otpRepository: OtpRepository) {}
OtpRepository.ts
#Injectable()
export class OtpRepository extends Repository<Otp> {
constructor(#InjectDataSource() private dataSource: DataSource) {
super(Otp, dataSource.createEntityManager());
}
UsersModule.ts
#Module({
imports: [OtpModule],
controllers: [],
providers: [],
})
export class UsersModule {}
When exporting the otp module as npm package got this error but if included the OtpModule within the project working fine
App compile successully

NestJS guard with GraphQL

I am trying to add an auth guard to a GraphQL resolver but it doesn't seem to be working as expected.
I have a simple guard that should reject all requests:
#Injectable()
export class AuthGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
return false;
}
}
and have applied it in a resolver:
#Resolver()
export class RecipeResolver {
#Query(() => [Recipe])
#UseGuards(AuthGuard)
public recipes(): Recipe[] {
return this.recipeData;
}
}
This does not work in the resolver and the canActivate is never fired. This does work in an HTTP Controller.
Changing #UseGuards(AuthGuard) to #UseGuards(new AuthGuard()) works but will not go through the dependency injection process which is not ideal.
What am I doing wrong?
Edit:
original app.module.ts:
#Module({
imports: [
GraphQLModule.forRoot({
autoSchemaFile: 'shcema.gql',
playground: true,
}),
RecipeResolver,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
From the code, the resolver was in the wrong location (in an imports array instead of providers) which meant Nest didn't set up the request lifecycle properly.

Nest.js this not working in constructor super

I try add configService to JwtStrategy:
constructor(readonly configService: ConfigService) {
super({
//...
secretOrKey: this.configService.get('SECRET_KEY'),
});
}
I'm using this instruction. But TS return me error:
'super' must be called before accessing 'this' in the constructor of a
derived class.
When I remove this (like in this answer), then Nest return another error:
Nest can't resolve dependencies of the JwtStrategy (?). Please make
sure that the argument ConfigService at index [0] is available in the
AuthModule context.
I fix it by adding ConfigService to providers in auth.module.ts file:
#Module({
controllers: [AuthController],
providers: [AuthService, JwtStrategy, ConfigService],
exports: [JwtStrategy],
})
I had to remove private from constructor and remove this from configService.

Can't use custom provider

I'm trying to inject a custom provider as per the documentation:
https://docs.nestjs.com/fundamentals/custom-providers
My service:
#Injectable({scope: Scope.REQUEST})
export class ReportService implements OnModuleInit {
private readonly reportRepository: Repository<Report>;
constructor(
public config: ConfigService,
private readonly moduleRef: ModuleRef,
#Inject('CONNECTION') connection: Connection,
) {
console.log(connection);
}
...
app.module.ts:
const connectionProvider = {
provide: 'CONNECTION',
useValue: connection,
};
#Module({
imports: [
ReportModule,
...
],
providers: [connectionProvider],
controllers: [AppController],
})
export class AppModule implements NestModule {
Doing so results in:
Error: Nest can't resolve dependencies of the ReportService (ConfigService, ModuleRef, ?). Please make sure that the argument at index [2] is available in the ReportModule context.
What am I missing?
If a provider should be available outside of the module you defined it in, you need to add it to exports in the module definition (app.module). The other module (report.module) using it needs to add the module to its imports definition.
app.module.ts
const connectionProvider = {
provide: 'CONNECTION',
useValue: Connection,
};
#Module({
imports: [
ReportModule,
...
],
providers: [connectionProvider],
exports: ['CONNECTION'],
controllers: [AppController],
})
export class AppModule implements NestModule {}
report.module.ts
#Module({
imports: [
AppModule
],
providers: [],
controllers: [],
})
export class ReportModule implements NestModule {}
In your case, this produces a circular dependency which needs to be resolved.
Since app.module seems to be your core module you could make it global but you still need to export the provider.
Alternatively, I found it to be a good practice to not define any providers in app.module and use DynamicModule (e.g. forRoot and forFeature static initiator functions) to only instantiate what is needed, but that seem to be outside of this question.

Resources