I am trying to import User Service which I exported from User Module inside authorization service but I am facing circular dependency issue and I have tried forwardRef() => UserService) but it doesn’t work.
Error message:
ERROR [ExceptionHandler] A circular dependency has been detected inside AuthModule. Please, make sure that each side of a bidirectional relationships are decorated with "forwardRef()". Note that circular relationships between custom providers (e.g., factories) are not supported since functions cannot be called more than once.
This is my authorization service
import { forwardRef, Inject, Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { User } from 'src/user/entity/user.entity';
import { LoginDto } from './dto/login.dto';
import * as bcrypt from 'bcrypt';
import { UserService } from 'src/user/user.service';
@Injectable()
export class AuthService {
constructor(
private jwtService: JwtService,
@Inject(forwardRef(() => UserService))
private userService: UserService,
) {}
async validateAdmin(email: string, password: string): Promise<User | null> {
const user = await this.userService.findOneByEmail(email);
if (user && await bcrypt.compare(password, user.password)) {
return user;
}
return null;
}
async login(loginDto: LoginDto) {
const user = await this.validateAdmin(loginDto.email, loginDto.password);
if (!user) {
throw new Error('Invalid credentials');
}
const payload = { email: user.email, role: user.role };
return {
access_token: this.jwtService.sign(payload),
};
}
}
My authorization module
import { Module } from '@nestjs/common';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { JwtModule } from '@nestjs/jwt';
import { JwtStrategy } from './jwt.strategy';
@Module({
imports: [
JwtModule.register({
secret: process.env.JWT_SECRET_KEY,
signOptions: { expiresIn: '1h' },
}),
],
controllers: [AuthController],
providers: [AuthService, , JwtStrategy],
})
export class AuthModule {}
1
add UserModule with forwardRef in AuthModules import like this:
@Module({
imports: [forwardRef(() => OtherModule)],
providers: [MyService],
exports: [MyService],
})
export class MyModule {}
dont forget to do the same in your UserModule like this:
@Module({
imports: [forwardRef(() => MyModule)],
providers: [OtherService],
exports: [OtherService],
})
export class OtherModule{}
then you can delete the implementation of forwardRefs in your service class