NestJS Nest can't resolve dependencies of the RolesService (+, +, ?) - javascript

Hi I'm programming using the NestJS framework (with MongoDB) and have build some modules now. When I try to import a model from another module it returns this error:
Nest can't resolve dependencies of the RolesService (+, +, ?).
Now, I've implemented the code like this:
app.module.ts
import { GroupsModule } from './groups/groups.module';
import { Module } from '#nestjs/common';
import { MongooseModule } from '#nestjs/mongoose';
import { UsersModule } from 'users/users.module';
import { RolesModule } from 'roles/roles.module';
#Module({
imports: [
MongooseModule.forRoot('mongodb://localhost:27017/example'),
UsersModule,
GroupsModule,
RolesModule,
],
providers: [],
})
export class AppModule {}
users.module.ts
import { Module } from '#nestjs/common';
import { MongooseModule } from '#nestjs/mongoose';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
import { RolesService } from 'roles/roles.service';
import { UserSchema } from './schemas/user.schema';
import { RoleSchema } from 'roles/schemas/role.schema';
#Module({
imports: [
MongooseModule.forFeature([{ name: 'User', schema: UserSchema }]),
MongooseModule.forFeature([{ name: 'Role', schema: RoleSchema }]),
],
controllers: [UsersController],
providers: [UsersService, RolesService],
exports: [UsersService],
})
export class UsersModule {}
users.service.ts
import { Model } from 'mongoose';
import { ObjectID } from 'mongodb';
import { InjectModel } from '#nestjs/mongoose';
import { Injectable, HttpException, HttpStatus } from '#nestjs/common';
import { User } from './interfaces/user.interface';
#Injectable()
export class UsersService {
constructor(#InjectModel('User') private readonly userModel: Model<User>) {}
}
groups.module.ts
import { MongooseModule } from '#nestjs/mongoose';
import { GroupsController } from './groups.controller';
import { RolesService } from '../roles/roles.service';
import { GroupsService } from './groups.service';
import { GroupSchema } from './schemas/group.schema';
import { UserSchema } from '../users/schemas/user.schema';
import { RoleSchema } from '../roles/schemas/role.schema';
#Module({
imports: [
MongooseModule.forFeature([{ name: 'Group', schema: GroupSchema }]),
MongooseModule.forFeature([{ name: 'User', schema: UserSchema }]),
MongooseModule.forFeature([{ name: 'Role', schema: RoleSchema }]),
],
controllers: [GroupsController],
providers: [GroupsService, RolesService],
exports: [GroupsService],
})
groups.service.ts
import { Injectable, HttpException, HttpStatus } from '#nestjs/common';
import { InjectModel } from '#nestjs/mongoose';
import { ObjectID } from 'mongodb';
import { Model } from 'mongoose';
import { Group } from './interfaces/group.interface';
import { User } from '../users/interfaces/user.interface';
import { CreateGroupDto } from './dto/create-group.dto';
import { RolesDto } from 'roles/dto/roles.dto';
import { Role } from '../roles/interfaces/role.interface';
#Injectable()
export class GroupsService {
constructor(#InjectModel('Group') private readonly groupModel: Model<Group>,
#InjectModel('Role') private readonly roleModel: Model<Role>) {} }
roles.module.ts
import { Module } from '#nestjs/common';
import { MongooseModule } from '#nestjs/mongoose';
import { RolesController } from './roles.controller';
import { RolesService } from './roles.service';
import { RoleSchema } from './schemas/role.schema';
import { UserSchema } from '../users/schemas/user.schema';
import { GroupSchema } from '../groups/schemas/group.schema';
#Module({
imports: [
MongooseModule.forFeature([{ name: 'User', schema: UserSchema }]),
MongooseModule.forFeature([{ name: 'Role', schema: RoleSchema }]),
MongooseModule.forFeature([{ name: 'Group', schema: GroupSchema }]),
],
controllers: [RolesController],
providers: [RolesService],
exports: [RolesService],
})
export class RolesModule {}
roles.service.ts
import { Injectable, HttpException, HttpStatus } from '#nestjs/common';
import { InjectModel } from '#nestjs/mongoose';
import { ObjectID } from 'mongodb';
import { Model } from 'mongoose';
import { Role } from './interfaces/role.interface';
import { User } from '../users/interfaces/user.interface';
import { Group } from '../groups/interfaces/group.interface';
import { CreateRoleDto } from './dto/create-role.dto';
import { RolesDto } from './dto/roles.dto';
#Injectable()
export class RolesService {
constructor( #InjectModel('Role') private readonly roleModel: Model<Role>,
#InjectModel('User') private readonly userModel: Model<User>,
#InjectModel('Group') private readonly groupModel: Model<Group> ) {} }
While the DI in the users and roles works fine, the error arise when I try to import the Group Model in the roles service. Please tell me if you see anything wrong, I've follow the same schema from users with groups but unfortunately can't see where the error lives.
Thanks in advance.
UPDATE: OK I think my error is when I try to use a module service function outside the module. I mean I modified (in order to simplify) I'll modify the code this way:
users.module.ts
#Module({
imports: [
MongooseModule.forFeature([{ name: 'User', schema: UserSchema }]),
RolesModule,
],
controllers: [UsersController],
providers: [UsersService, RolesService],
exports: [UsersService],
})
export class UsersModule {}
users.controller.ts
export class UsersController {
constructor(private readonly usersService: UsersService,
private readonly rolesService: RolesService){}
async addRoles(#Param('id') id: string, #Body() userRolesDto: UserRolesDto): Promise<User> {
try {
return this.rolesService.setRoles(id, userRolesDto);
} catch (e){
const message = e.message.message;
if ( e.message.error === 'NOT_FOUND'){
throw new NotFoundException(message);
} else if ( e.message.error === 'ID_NOT_VALID'){
throw new BadRequestException(message);
}
}
}
}
roles.module.ts
#Module({
imports: [
MongooseModule.forFeature([{ name: 'Role', schema: RoleSchema }]),
],
controllers: [RolesController],
providers: [RolesService],
exports: [RolesService],
})
export class RolesModule {}
roles.service.ts
#Injectable()
export class RolesService {
userModel: any;
constructor( #InjectModel('Role') private readonly roleModel: Model<Role> ) {}
// SET USER ROLES
async setRoles(id: string, rolesDto: RolesDto): Promise<User> {
if ( !ObjectID.isValid(id) ){
throw new HttpException({error: 'ID_NOT_VALID', message: `ID ${id} is not valid`, status: HttpStatus.BAD_REQUEST}, 400);
}
try {
const date = moment().valueOf();
const resp = await this.userModel.updateOne({
_id: id,
}, {
$set: {
updated_at: date,
roles: rolesDto.roles,
},
});
if ( resp.nModified === 0 ){
throw new HttpException({ error: 'NOT_FOUND', message: `ID ${id} not found or entity not modified`, status: HttpStatus.NOT_FOUND}, 404);
} else {
let user = await this.userModel.findOne({ _id: id });
user = _.pick(user, ['_id', 'email', 'roles', 'created_at', 'updated_at']);
return user;
}
} catch (e) {
if ( e.message.error === 'NOT_FOUND' ){
throw new HttpException({ error: 'NOT_FOUND', message: `ID ${id} not found or entity not modified`, status: HttpStatus.NOT_FOUND}, 404);
} else {
throw new HttpException({error: 'ID_NOT_VALID', message: `ID ${id} is not valid`, status: HttpStatus.BAD_REQUEST}, 400);
}
}
}
That's it, as you can see when I try to use from users.controller the roles.service setRole method it returns me an error:
Nest can't resolve dependencies of the RolesService (?). Please make sure that the argument at index [0]is available in the current context.
I don't understand where the problem is because I'm injecting the Role model in the roles.module already and it don't understand it. In fact if I don't create the call from users.module to this dependency everything goes fine.
Any tip?
(I've red the suggestion from stackoverflow, I'll don't do it again)

I think the problem is that you're importing the same model multiple times, like:
MongooseModule.forFeature([{ name: 'User', schema: UserSchema }]
and also providing the same service multiple times:
providers: [RolesService]
I would not inject the models themselves but rather the corresponding services that encapsulate the model. Then you export the service in its module and import the module where needed. So the RolesService would inject the UsersSerivce instead of the UserModel.
With your current setup, you would run into circular dependencies though. This can be handled with fowardRef(() => UserService) but should be avoided if possible, see the circular dependency docs. If this is avoidable depends on your business logic however.
If you don't have circular dependencies then for example export your RolesService
#Module({
imports: [MongooseModule.forFeature([{ name: 'Role', schema: RoleSchema }])]
controllers: [RolesController],
providers: [RolesService],
exports: [RolesService],
})
export class RolesModule {}
and import the RolesModule wherever you want to use the RolesService, e.g.:
#Module({
imports: [
RolesModule,
MongooseModule.forFeature([{ name: 'User', schema: UserSchema }])
],
controllers: [UsersController],
providers: [UsersService],
exports: [UsersService],
})

Related

Everything is imported but Nest can't resolve dependencies of the stripePaymentService

I am integrating Stripe payment gateway through NestJS. I am getting the error which says "Nest can't resolve dependencies of the stripePaymentService". Although I am quite familiar with this error but somehow things are not working for me. I believe everything is imported where it should be.
This is complete error:
Error: Nest can't resolve dependencies of the stripePaymentService (?). Please make sure that the argument paymentIntentRepository at index [0] is available in the AppModule context.
Potential solutions:
- Is AppModule a valid NestJS module?
- If paymentIntentRepository is a provider, is it part of the current AppModule?
- If paymentIntentRepository is exported from a separate #Module, is that module imported within AppModule?
My stripePaymentModule is
/* eslint-disable prettier/prettier */
import { Module } from '#nestjs/common';
import { stripePaymentController } from './stripe-payment.controller';
import { stripePaymentService } from './stripe-payment.service';
import { TypeOrmModule } from '#nestjs/typeorm';
import { paymentIntent } from './entities/paymentIntent.entity';
import { ConfigModule } from '#nestjs/config';
#Module({
imports:[
ConfigModule.forRoot({
isGlobal: true,
}),
TypeOrmModule.forFeature([paymentIntent])],
controllers: [stripePaymentController],
providers: [stripePaymentService],
exports: [stripePaymentService],
})
export class stripePaymentModule {}
stripePaymentServices is
/* eslint-disable prettier/prettier */
import { Injectable, Logger } from '#nestjs/common';
import { InjectStripe } from 'nestjs-stripe';
import { ConfigService } from '#nestjs/config';
import Stripe from 'stripe';
import { paymentIntent } from './entities/paymentIntent.entity';
import { InjectRepository } from '#nestjs/typeorm';
import { Repository } from 'typeorm';
#Injectable()
export class stripePaymentService {
stripe: Stripe;
logger = new Logger(stripePaymentService.name);
constructor(
#InjectRepository(paymentIntent)
private readonly paymentIntent:Repository<paymentIntent>,
)
{const stripeApiKey = process.env.STRIPE_SECRET_KEY;
this.stripe = new Stripe(stripeApiKey, {
apiVersion: '2022-11-15',
});}
async payment_intent(data: any, user) {
const intent = await this.stripe.paymentIntents.create({
amount: data.amount,
currency: data.currency,
description: data.description,
payment_method_types: ['card'],
});
return await this.paymentIntent.save({'userId':user.userId, 'intent_response':JSON.stringify(intent)})
// return intent;
}
}
And finally this is app.module
/* eslint-disable prettier/prettier */
import { Module } from '#nestjs/common';
import { UsersModule } from './users/users.module';
import { ConfigModule, ConfigService } from '#nestjs/config';
import { TypeOrmModule } from '#nestjs/typeorm';
import { AuthModule } from './auth/auth.module';
import { User } from './users/entities/user.entity';
import { PassportModule } from '#nestjs/passport';
import { MailModule } from './mail/mail.module';
import { FlightBookingModule } from './flight-booking/flight-booking.module';
import { TravelBookings } from './flight-booking/entities/bookingToken.entity';
import { stripePaymentService } from './stripe/stripe-payment.service';
import { stripePaymentController } from './stripe/stripe-payment.controller';
import { StripeModule } from 'nestjs-stripe';
import { stripePaymentModule } from './stripe/stripe-payment.module';
import { paymentIntent } from './stripe/entities/paymentIntent.entity';
#Module({
imports: [
ConfigModule.forRoot({ isGlobal: true }),
StripeModule.forRoot({
apiKey: process.env.STRIPE_API_KEY,
apiVersion: '2022-11-15'
}),
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
useFactory: (configService: ConfigService) => ({
type: 'postgres',
host: configService.get('DB_HOST'),
port: +configService.get<number>('DB_PORT'),
username: configService.get('DB_USERNAME'),
password: configService.get('DB_PASSWORD'),
database: configService.get('DB_NAME'),
entities: [User, TravelBookings, paymentIntent],
synchronize: true,
}),
inject: [ConfigService],
}),
PassportModule,
UsersModule,
AuthModule,
MailModule,
FlightBookingModule,
stripePaymentModule
],
controllers: [stripePaymentController],
providers: [stripePaymentService],
})
export class AppModule {}
The error is thrown from AppModule context. You wouldn't need to put stripePaymentService as a provider in AppModule.
If stripePaymentService is used by other modules, once you have export it, you just need to import the related module in a module that you want, and that would be enough.
So all you need to do is remove these lines from AppModule:
providers: [stripePaymentService]
You can remove this line as well:
controllers: [stripePaymentController]

Nest can't resolve dependencies of the service?

I'm trying access a database using a custom provider as per this guide. At startup, Nestjs throws the error Nest can't resolve dependencies of the EventsService (?). Please make sure that the argument DATA_SOURCE at index [0] is available in the AppModule context.
Here are my files
Database providers
import { DataSource } from 'typeorm';
export const databaseProviders = [
{
provide: 'DATA_SOURCE',
useFactory: async () => {
const dataSource = new DataSource({
type: "mysql",
host: "host",
port: 3306,
username: "username",
password: "password",
synchronize: true,
logging: true,
});
return dataSource.initialize();
},
},
];
Database module
import { databaseProviders } from "./database.providers";
import { Module } from "#nestjs/common";
#Module({
providers: [...databaseProviders],
exports: [...databaseProviders],
})
export class DatabaseModule {}
Events service
import { Inject, Injectable } from '#nestjs/common';
import { DataSource } from 'typeorm';
import { DatabaseModule } from './database.module';
import { Event } from './entities/event.entity';
import { EventInvite } from './entities/eventInvite.entity';
#Injectable()
export class EventsService {
constructor(#Inject("DATA_SOURCE") private readonly database: DataSource) { }
createEvent(userId: string, event: Event) {
this.database.manager.create(Event, event)
}
deleteEvent(eventId: string){
this.database.manager.delete(Event, { eventId })
}
}
Events Module
import { Module } from '#nestjs/common';
import { DatabaseModule } from './database.module';
import { EventsController } from './events.controller';
import { EventsService } from './events.service';
#Module({
imports: [DatabaseModule],
controllers: [EventsController],
providers: [EventsService],
exports: [EventsService]
})
export class EventsModule {}
App module
import { Module } from '#nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { EventsController } from './events/events.controller';
import { EventsService } from './events/events.service';
import { EventsModule } from './events/events.module';
import { DatabaseModule } from './events/database.module';
#Module({
imports: [],
controllers: [AppController, EventsController],
providers: [AppService, EventsService],
})
export class AppModule {}
If I import DatabaseModule inside of AppModule everything works. My question is, why is this required? My understanding thus far is that Nestjs builds a dependency tree, which in this case should look something like AppModule => EventService => DatabaseService. AppModule doesn't directly access DatabaseService, and therefore shouldn't need to import it directly, so why is Nestjs failing to resolve this dependency?
that module isn't global, thus its providers aren't globally available. As you're registering the service EventsService again in AppModule, you need to import the DatabaseModule
I believe this is what you're trying to do (which is pretty much what the docs shows):
#Module({
imports: [EventsModule],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
than you won't have 2 instances of EventsService and EventsController anymore, only the one registered in EventsModule module.

How to fix NestJS #InjectModel() dependency error?

rememberLink.scheme.ts
import { Prop, Schema, SchemaFactory } from '#nestjs/mongoose';
import { Document, Types } from 'mongoose';
import { User } from 'src/users/schemas/users.schema';
export type RememberLinkDocument = RememberLink & Document;
#Schema({versionKey: false, timestamps: true})
export class RememberLink {
#Prop({ type: String, required: true })
code: string;
#Prop({ type: Types.ObjectId, ref: User.name, required: true })
user: User;
}
export const RememberLinkSchema = SchemaFactory.createForClass(RememberLink);
remember-password.module.ts
import { Module } from '#nestjs/common';
import { MongooseModule } from '#nestjs/mongoose';
import { RememberPasswordController } from './remember-password.controller';
import { RememberPasswordService } from './remember-password.service';
import { RememberLink, RememberLinkSchema } from './schemas/rememberLink.schema';
#Module({
imports: [
MongooseModule.forFeature([{
name: RememberLink.name,
schema: RememberLinkSchema
}])
],
controllers: [RememberPasswordController],
providers: [RememberPasswordService],
exports: [RememberPasswordService]
})
export class RememberPasswordModule {}
remember-password.service.ts
import { Injectable } from '#nestjs/common';
import { InjectModel } from '#nestjs/mongoose';
import { Model } from 'mongoose';
import { UserDto } from 'src/users/dto/user.dto';
import { User } from 'src/users/schemas/users.schema';
import { RememberLinkDto } from './dto/rememberLink.dto';
import { RememberLink, RememberLinkDocument } from './schemas/rememberLink.schema';
#Injectable()
export class RememberPasswordService {
constructor( #InjectModel(RememberLink.name) private readonly rememberLinkModel: Model<RememberLinkDocument> ) {}
async getUserByRememberCode(code: string): Promise<UserDto> {
return await this.rememberLinkModel.findOne({code}).populate(User.name).lean();
}
}
Error:
Nest can't resolve dependencies of the RememberPasswordService (?).
Please make sure that the argument RememberLinkModel at index [0] is
available in the RememberPasswordService context.
What I would do is export the MongooseModule as well, Its just that the dependency injection knows that there will be Separate module for that model somewhere in the App
#Module({
imports: [
MongooseModule.forFeature([{
name: RememberLink.name,
schema: RememberLinkSchema
}])
],
controllers: [RememberPasswordController],
providers: [RememberPasswordService],
exports: [MongooseModule,RememberPasswordService] // <-- MongooseModule added here
})
export class RememberPasswordModule {}
Fixed. It was import "RememberPasswordService" instead of "RememberPasswordModule" in another module

ngx-translate with Angular universal has problems translating parameterised value

I'm working on migrating my Angular 10 application to SSR using Angular universal and I'm facing issues with ngx-translate while translating parameterised values.
I have a translation
Bei Kauf von {quantity}
where this quantity is an attribute from our component and we normally translate it like
{{ 'LABEL' | translate: {quantity: 1} }} and we will see Bei Kauf von 1
But with SSR it's not at all translating. I see Bei Kauf von {quantity} on the page. I checked many forums and I don't see potential solutions. Any help would be much appreciated.
Here is my translate-server.loader.ts
import { join } from 'path';
import { Observable } from 'rxjs';
import { TranslateLoader } from '#ngx-translate/core';
import {
makeStateKey,
StateKey,
TransferState
} from '#angular/platform-browser';
import * as fs from 'fs';
export class TranslateServerLoader implements TranslateLoader {
constructor(
private transferState: TransferState,
private prefix: string = 'i18n',
private suffix: string = '.json'
) {}
public getTranslation(lang: string): Observable<any> {
return new Observable((observer) => {
const assets_folder = join(
process.cwd(),
'dist',
'my-app',
'browser',
'assets',
this.prefix
);
const jsonData = JSON.parse(
fs.readFileSync(`${assets_folder}/${lang}${this.suffix}`, 'utf8')
);
// Here we save the translations in the transfer-state
const key: StateKey<number> = makeStateKey<number>(
`transfer-translate-${lang}`
);
this.transferState.set(key, jsonData);
observer.next(jsonData);
observer.complete();
});
}
}
export function translateServerLoaderFactory(transferState: TransferState) {
return new TranslateServerLoader(transferState);
}
translate-browser.loader.ts
import { Observable } from 'rxjs';
import { TranslateLoader } from '#ngx-translate/core';
import {
makeStateKey,
StateKey,
TransferState
} from '#angular/platform-browser';
import { TranslateHttpLoader } from '#ngx-translate/http-loader';
import { HttpClient } from '#angular/common/http';
export class TranslateBrowserLoader implements TranslateLoader {
constructor(private http: HttpClient, private transferState: TransferState) {}
public getTranslation(lang: string): Observable<any> {
const key: StateKey<number> = makeStateKey<number>(
`transfer-translate-${lang}`
);
const data = this.transferState.get(key, null);
// First we are looking for the translations in transfer-state,
// if none found, http load as fallback
if (data) {
return new Observable((observer) => {
observer.next(data);
observer.complete();
});
} else {
return new TranslateHttpLoader(this.http).getTranslation(lang);
}
}
}
export function translateBrowserLoaderFactory(
httpClient: HttpClient,
transferState: TransferState
) {
return new TranslateBrowserLoader(httpClient, transferState);
}
app.server.module.ts
import { NgModule } from '#angular/core';
import { ServerModule, ServerTransferStateModule } from '#angular/platform-server';
import { FlexLayoutServerModule } from '#angular/flex-layout/server';
import { TranslateModule, TranslateLoader } from '#ngx-translate/core';
import { translateServerLoaderFactory } from './shared/loaders/translate-server.loader';
import { TransferState } from '#angular/platform-browser';
import { AppModule } from './app.module';
import { AppComponent } from './app.component';
import { EnvironmentService } from '~shared/services/environment.service';
#NgModule({
imports: [
AppModule,
ServerModule,
ServerTransferStateModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: translateServerLoaderFactory,
deps: [TransferState]
}
}),
FlexLayoutServerModule,
],
providers: [EnvironmentService],
bootstrap: [AppComponent],
})
export class AppServerModule {}
app.module.ts
imports: [
....,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: translateBrowserLoaderFactory,
deps: [HttpClient, TransferState]
}
}),
]
Note: It's working fine for all others which don't have any parameterised values in translations
It should be double curly brackets
Bei Kauf von {{quantity}}
wanna notice 2 more things, idk if it changed in last versions of Angular, but don't forget to register TransferState in app.module providers
providers: [
TransferState,
...
]
and for translate-server.loader.ts if you have some type errors for node.js use
/// <reference types="node" /> // add this line
import {join} from 'path';
at the top.
If it doesn't help, try to add
"types" : ["node", "express"],
to your tsconfig.json inside "compilerOptions"
It took me some time))

NestJS JwtModule.registerAsync() gives undefined at imports

when I nest start the code, it gives follow error, what is the problem?
I set ConfigModule as Gloabl, so I shouldn't need to import.
If I missed any code, please tell me, I can post it here.
I reference usage in NestJS Jwt package
I previously use JwtModule.register() with hardcoded secrets and options, it works fine.
[Nest] 159128 - 02/27/2021, 6:27:15 PM [ExceptionHandler] Nest cannot create the AuthModule instance.
The module at index [2] of the AuthModule "imports" array is undefined.
Potential causes:
- A circular dependency between modules. Use forwardRef() to avoid it. Read more: https://docs.nestjs.com/fundamentals/circular-dependency
- The module at index [2] is of type "undefined". Check your import statements and the type of the module.
TyprOrmModule access the database just fine, it proves configService picks up environment variables in .env
AppModule.ts:
import { Module } from '#nestjs/common';
import { AppController } from './app.controller';
import { TypeOrmModule } from '#nestjs/typeorm';
import { Connection } from 'typeorm';
import { join } from 'path';
import { UserModule } from './user/user.module';
import { AuthModule } from './auth/auth.module';
import { FormModule } from './form/form.module';
import { InventoryModule } from './inventory/inventory.module';
import { ConfigModule, ConfigService } from '#nestjs/config';
#Module({
imports: [
ConfigModule.forRoot({
isGlobal: true
//, ignoreEnvFile: true
}),
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
useFactory: (configService: ConfigService) => ({
type: 'mysql',
host: configService.get('DB_HOST'),
port: configService.get<number>('DB_PORT'),
username: configService.get('DB_USERNAME'),
password: configService.get('DB_PASSWORD'),
database: configService.get('DB_DATABASE'),
synchronize: true,
autoLoadEntities: true,
}),
inject: [ConfigService],
})
, UserModule, AuthModule, FormModule, InventoryModule,
],
controllers: [AppController],
})
export class AppModule {
constructor(private connection: Connection) { }
}
if I add imports ConfigModule and inject ConfigService, it gives exact error at nest start. I just can't identify where the problem is.
AuthModule.ts:
import { Module } from '#nestjs/common';
import { AuthController } from './auth.controller';
import { LdapStrategy } from './ldap/ldap.strategy';
import { AuthService } from './auth.service';
import { JwtModule } from '#nestjs/jwt';
import { PassportModule } from '#nestjs/passport';
import { jwtConstants } from './jwt/constants';
import { JwtStrategy } from './jwt/jwt.strategy';
import { UserModule } from 'src/user/user.module';
import { JwtRefreshTokenStrategy } from './jwt/jwt.refresh.strategy';
import { ConfigModule, ConfigService } from '#nestjs/config';
#Module({
imports: [
PassportModule,
//ConfigModule,
JwtModule.registerAsync({
//imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({
secret: configService.get<string>('JWT_SECRET'),
// signOptions: {
// algorithm: 'HS256',
// expiresIn: configService.get<number>('JWT_EXPIRES_IN_SEC'),
// }
}),
//inject: [ConfigService],
}),
, UserModule
],
controllers: [AuthController],
providers: [
LdapStrategy
, AuthService
, JwtStrategy
, JwtRefreshTokenStrategy
],
//exports: [AuthService],
})
export class AuthModule { }
Although this answer is pretty late, I ran into the exact same issue and found the solution on the Github site for #nestjs/jwt (https://github.com/nestjs/jwt#async-options). Posting here just in case anyone else runs into it.
It appears that you also need to inject the ConfigService as well.
JwtModule.registerAsync({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({
secret: configService.get<string>('SECRET'),
}),
inject: [ConfigService],
})

Categories

Resources