Reputation: 2520
I'm new in NEST.js world, and I trying to create simple middleware. First, I created a middleware with this command:
nest g middleware common/middleware/logging
And after I add my code
import { Injectable, NestMiddleware } from '@nestjs/common';
@Injectable()
export class LoggingMiddleware implements NestMiddleware {
use(req: any, res: any, next: () => void) {
console.time('Request-response time');
console.log('Hi from middleware!');
res.on('finish', () => console.timeEnd('Request-response time'));
next();
}
}
And finally, I add the middleware
import { Module, MiddlewareConsumer } from '@nestjs/common';
import { APP_GUARD } from '@nestjs/core';
import { ApiKeyGuard } from './guards/api-key.guard';
import { ConfigModule } from '@nestjs/config';
import { LoggingMiddleware } from './middleware/logging.middleware';
@Module({
imports: [
ConfigModule
],
providers: [
{
provide: APP_GUARD,
useClass: ApiKeyGuard
}
]
})
export class CommonModule {
constructor(consumer: MiddlewareConsumer) {
consumer.apply(LoggingMiddleware).forRoutes('*')
}
}
But when i try to run it:
Nest can't resolve dependencies of the CommonModule (?). Please make sure that the argument Object at index [0] is available in the CommonModule context.
Potential solutions:
- If Object is a provider, is it part of the current CommonModule?
- If Object is exported from a separate @Module, is that module imported within CommonModule? @Module({ imports: [ /* the Module containing Object */ ] }) +2ms Error: Nest can't resolve dependencies of the CommonModule (?). Please make sure that the argument Object at index [0] is available in the CommonModule context.
Potential solutions:
- If Object is a provider, is it part of the current CommonModule?
- If Object is exported from a separate @Module, is that module imported within CommonModule? @Module({ imports: [ /* the Module containing Object */ ] })
Can you help me?
Upvotes: 0
Views: 1280
Reputation: 70061
The MiddlewareConsumer
isn't a part of the constructor
. Rather, your module class should implement NestModule
and should have a configure
method that takes in the consumer: MiddlewareConsumer
as the first and only paramter.
@Module({
imports: [
ConfigModule
],
providers: [
{
provide: APP_GUARD,
useClass: ApiKeyGuard
}
]
})
export class CommonModule implmenets NestModule {
configure(consumer: MidlewareConsumer) {
consumer.apply(LoggingMiddleware).forRoutes('*')
}
}
Upvotes: 1