node.js - problema nestjs - Nest não consegue resolver as dependências do AuthenticationService (?)
O aplicativo para imediatamente ao iniciar, outros módulos ainda não foram verificados, então é improvável que o erro esteja neles.
authentication.service.ts
import { HttpException, HttpStatus, Inject, Injectable } from '@nestjs/common';
import { CreateUserDto } from 'src/users/dto/createUser.dto';
import { UserService } from 'src/users/user/user.service';
import bcrypt from 'bcrypt';
@Injectable()
export class AuthenticationService {
constructor(@Inject() private readonly userService: UserService){}
public async regiser(registartionData:CreateUserDto){
const hashingPassword = await bcrypt.hash(registartionData.passwordHash, 10);
try{
const createUser = await this.userService.create({
...registartionData,
passwordHash: hashingPassword
})
createUser.passwordHash = undefined;
return createUser;
}
catch(err){
throw new HttpException('Something went wrong', HttpStatus.INTERNAL_SERVER_ERROR);
}
}
public async getAuthenticationUser(email:string, textPassword:string){
try{
const user = await this.userService.findByEmail(email);
await this.verifyPassword(textPassword,user.passwordHash);
user.passwordHash = undefined;
return user;
}
catch(err){
throw new HttpException('Wrong credentials provided', HttpStatus.BAD_REQUEST);
}
}
private async verifyPassword(password:string, hashingPassword:string){
const isMatching = await bcrypt.compare(password, hashingPassword);
if(!isMatching) throw new HttpException('Wrong credentials provided', HttpStatus.BAD_REQUEST);
}
}
auth.module.ts
import { Module } from '@nestjs/common';
import { PassportModule } from '@nestjs/passport';
import { UsersModule } from 'src/users/users.module';
import { AuthController } from '../controllers/auth/auth.controller';
import { AuthenticationService } from './authentication/authentication.service';
import { LocalStrategy } from './authentication/local.strategy';
@Module({
imports:[UsersModule, PassportModule, ],
providers: [AuthenticationService, LocalStrategy],
controllers:[AuthController],
exports: [AuthenticationService]
})
export class AuthModule {}
este erro
Nest can't resolve dependencies of the AuthenticationService (?). Please make sure that the argument dependency at index [0] is available in the AuthModule context.
Potential solutions:
- If dependency is a provider, is it part of the current AuthModule?
- If dependency is exported from a separate @Module, is that module imported within AuthModule?
@Module({
imports: [ /* the Module containing dependency */ ]
})
Eu não entendo o erro, exporte e forneça o serviço de autenticação. Eu não uso o serviço de autenticação em outros módulos.
Resposta #1
Todos os meus serviços usam o modelo mongodb. Portanto, você precisa fazer o seguinte nos módulos e serviços.
usuário.módulo.ts
@Module({
*imports: [MongooseModule.forFeature([{ name: 'User', schema: UserSchema }])],*
providers: [UserService],
exports: [UserService],
})
export class UsersModule {}
user.service.ts
@Injectable()
export class UserService implements IUserService {
constructor(
*@InjectModel(User.name) private userModel: Model<User>*
) {}
bom exemplo https://wanago.io/2021/08/23/api-nestjs-relationships-mongodb/
Resposta #2
O código no seu repositório não pode nem ser compilado, então quase não posso te ajudar. Faltam coisas, erros de TS, etc.
mas pelo que eu vejo:
- O módulo UsersModule tem o provedor
UserService, mas não o está exportando. Portanto, NENHUM OUTRO MÓDULO teria acesso a ele. Você precisa exportar o UserService também. - O AuthModule não importa o UserService (e nada o exporta), então ele não é encontrado no momento em que o Nest tenta casar as injeções. O que você pode fazer é adicionar
imports: [UserModule]no AuthModule (e também exportar o UserService no UserModule).
E leia novamente a documentação dos módulos e do projeto de exemplo para ver como funcionam importações, exportações, controladores e provedores.
