Home > Software design >  Error compiling Nest js APP - Nest can't resolve dependencies of the UsersService (?)
Error compiling Nest js APP - Nest can't resolve dependencies of the UsersService (?)

Time:01-31

Im learning NestJs and using a tutorial to install User Auth with JWT

I have a user module which on its on works great but with the new auth service Im getting the error

Error: Nest can't resolve dependencies of the UsersService (?). Please make sure that the argument UsersModel at index [0] is available in the AuthModule context.

The auth module is as follows:

import { Module } from "@nestjs/common"
import { UsersModule } from "../users/users.module";
import { AuthService } from "./auth.service"
import { PassportModule } from "@nestjs/passport"
import { JwtModule } from '@nestjs/jwt';
import { AuthController } from './auth.controller';
import { UsersService } from "../users/users.service";
import { MongooseModule } from "@nestjs/mongoose"
import { UserSchema } from "users/schemas/users.schema";
import { LocalStrategy } from './local.auth';

@Module({
  imports: [UsersModule, PassportModule, JwtModule.register({
    secret: 'secretKey',
    signOptions: { expiresIn: '60s' },
  }), MongooseModule.forFeature([{ name: "user", schema: UserSchema }])],
  providers: [AuthService, UsersService, LocalStrategy],
  controllers: [AuthController],
})
export class AuthModule { }

And the users service

import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { User } from 'users/interfaces/users.interface';

@Injectable()
export class UsersService {
    constructor(@InjectModel('Users') private readonly userModel: Model<User>) {}

    //Get all users
    async getUsers(): Promise<User[]> {
        const users = await this.userModel.find().exec();
        return users
    }

    //Get single user
    async getUser(query: object ): Promise<User> {
        return this.userModel.findOne(query);
    }

    async addUser(
        firstname: string, 
        lastname: string, 
        jobtitle: string, 
        startdate: string,
        password: string,
        email: string): Promise<User> {
        return this.userModel.create({
            firstname,
            lastname,
            jobtitle,
            startdate,
            password,
            email
        });
    }

}

And for context the auth service and user interface

import { Injectable } from '@nestjs/common';
import { UsersService } from 'src/users/users.service';
import * as bcrypt from 'bcrypt';
import { JwtService } from '@nestjs/jwt';
import { NotAcceptableException } from '@nestjs/common/exceptions';

@Injectable()
export class AuthService {
    constructor(private readonly usersService: UsersService, private jwtService: JwtService) {}
    async validateUser(email: string, password: string): Promise<any> {
        const user = await this.usersService.getUser({email});
        if(!user) return null;
        const passwordValid = await bcrypt.compare(password, user.password)
    if(!user) {
        throw new NotAcceptableException('could not find the user');
    }
    if(user && passwordValid) {
        return user;
    }
    return null;
    }
    async login(user: any) {
        const payload = {username: user.username, sub: user._id};
        return {
            access_token: this.jwtService.sign(payload),
        };
    }
}
import { Document } from "mongoose";

export interface User extends Document {
    readonly firstname: string;
    readonly lastname: string;
    readonly jobtitle: string;
    readonly startdate: string;
    readonly password: string;
    readonly email: string;
}

So I have checked to make sure all imports are correct which they are and made sure all modules are aware of the imports needed - so Im a little stumped

CodePudding user response:

So long as your UserModule has exports: [UserService] you can remove the UserService from the AuthModule's providers array. Every time you add a provider to a providers array you are telling Nest to create that provider in the context of the current module, and not possibly re-use one even if it exists in an imported module.

CodePudding user response:

To add to jay's answer, You need this line in your users.module.ts not in auth.module.ts

MongooseModule.forFeature([{ name: "user", schema: UserSchema }])]

also, the name you provide here should be the same in @InjectModel('Users'), you have "user" here and 'Users' there.

  • Related