After diving into the nestjs docs and exploring hierarchical injection, I found myself struggling to properly implement it within my project. Currently, I have two crucial modules at play.
AuthModule
is responsible for importing the UserModule
, which contains a service utilized by other modules where it functions flawlessly.
auth.module.ts
import * as passport from 'passport';
import {
Module,
NestModule,
MiddlewaresConsumer,
RequestMethod,
} from '@nestjs/common';
import { AuthService } from './auth.service';
import {JwtStrategy} from './jwt.straegy';
import {UserModule} from '../shared/user/user.module';
@Module({
imports: [UserModule],
components: [AuthService, JwtStrategy],
exports: [AuthService]
})
export class AuthModule implements NestModule {
public configure(consumer: MiddlewaresConsumer) {
consumer
.apply(passport.authenticate('jwt', { session: false }))
.forRoutes({ path: '/cats', method: RequestMethod.ALL });
}
}
user.module.ts
import {Module} from '@nestjs/common';
import {MongooseModule} from '@nestjs/mongoose';
import {UserSchema} from '../../schema/user.schema';
import {UserService} from './user.service';
@Module({
imports: [
MongooseModule.forFeature([{ name: 'UserInterface', schema: UserSchema }])
],
components: [UserService],
exports: [UserService]
})
export class UserModule {}
The issue arises when UserService is injected into AuthService within the nestjs framework, resulting in an error notification. Strangely enough, UserService operates smoothly in other modules.
Error: Nest can't resolve dependencies of the AuthService (?). Please verify whether [0] argument is available in the current context.
auth.service.ts
import * as jwt from 'jsonwebtoken';
import { Component } from '@nestjs/common';
import {UserService} from '../shared/user/user.service';
@Component()
export class AuthService {
constructor(private readonly userService: UserService) {}
async createToken(username) {
const expiresIn = 60 * 60, secretOrKey = 'i am fake!';
const user = {username};
const token = jwt.sign(user, secretOrKey, {expiresIn});
return {
expires_in: expiresIn,
access_token: token
};
}
async validateUser(signedUser): Promise<boolean> {
return !!(await this.userService.findByUsername(signedUser.username));
}
}