Reputation: 285
I'm trying to make application using nestjs
Dependency injection into controller works well so far.
But when I inject service into passport strategy, injecting is not working.
I want to inject authService
into googleStrategy
.
This is my module code.
auth.modules.ts
@Module({
imports: [
UsersModules,
PassportModule,
],
controllers: [AuthController],
providers: [AuthService, GoogleStrategy],
})
export class AuthModules {}
google.strategy.ts
@Injectable()
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
constructor(private authService: AuthService) {
super({ /*...*/ });
console.log(this.authService) //undefined
}
}
In this case, AuthService
is not injected.
When I inject AuthService
manually using @Inject
decorator, AuthService
injected successfully.
constructor(@Inject('AuthService') private authService: AuthService) {
super({ /*...*/ });
console.log(this.authService) // AuthService is injected
}
Why service is not injected into passport strategy?
Upvotes: 4
Views: 1639
Reputation: 41
i think that you want to do something like this
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { config } from 'dotenv';
import { UserService } from 'src/user/user.service';
import { Injectable } from '@nestjs/common';
config();
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
constructor(private readonly UserSerive: UserService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: process.env.jwt_secret,
});
}
async validate(payload: any) {
return {
user: payload.sub,
username: payload.username,
id: payload.id,
roles: (await this.UserSerive.findOne(payload.id)).roles,
};
}
}
Upvotes: 2
Reputation: 641
Try to register your AuthService
in AuthModule
like this:
providers: [
{
provide: 'AUTH_SERVICE',
useClass: AuthService
},
GoogleStrategy
]
And then, in GoogleStrategy
class, in constructor write this:
constructor(@Inject('AUTH_SERVICE') private authService: AuthService)
Upvotes: 0