Nest can't resolve DataSource as dependency in my custom module - nestjs

I've had a problem with dependencies in NestJS. On launch my NestJS app, compiler throw me this:
Nest can't resolve dependencies of the OtpRepository (?). Please make sure that the argument DataSource at index [0] is available in the TypeOrmModule context.
OtpModule.ts
#Global()
#Module({
imports: [TypeOrmModule.forFeature([Otp])],
providers: [
OtpService,
OtpRepository,
],
exports: [TypeOrmModule, OtpService, OtpRepository],
})
export class OtpModule {}
OtpService.ts
#Injectable()
export class OtpService {
constructor(private readonly otpRepository: OtpRepository) {}
OtpRepository.ts
#Injectable()
export class OtpRepository extends Repository<Otp> {
constructor(#InjectDataSource() private dataSource: DataSource) {
super(Otp, dataSource.createEntityManager());
}
UsersModule.ts
#Module({
imports: [OtpModule],
controllers: [],
providers: [],
})
export class UsersModule {}
When exporting the otp module as npm package got this error but if included the OtpModule within the project working fine
App compile successully

Related

Nestjs middleware with dependencies

I am having trouble creating a middleware that has two dependencies (TypeORModule.forFeature([USER]), FirebaseModule).
What I have done is create an AuthModule which looks like this:
#Module({
imports: [
FirebaseModule,
TypeOrmModule.forFeature([User])
],
providers: [
AuthMiddleware
],
})
and the middleware which looks like this
export class AuthMiddleware implements NestMiddleware {
constructor(
#InjectRepository(User)
private usersRepository: Repository<User>,
private firebaseService: FirebaseService
) {}
async use(req: Request, res: Response, next: () => void) {...}
}
and my app module which looks like this
#Module({
imports: [
TypeOrmModule.forRoot({
...config.get("database"),
entities: [__dirname + '/entities/**/*.{js,ts}']
}),
AuthModule,
exampleModule
],
providers: [
AuthMiddleware
]
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer): any {
consumer.apply(AuthMiddleware).forRoutes("*")
}
}
I get many errors and I try to shift things around to make it work but I simply can't get it to happen. I get errors from
Please make sure that the argument UserRepository at index [0] is available in the module(sometimes AppModule, sometimes exampleModule) context.
Do other modules (controller ones, as in providing api services) need to also import the middleware module if it applies to them too?
In general, how do I go on about implementing middlewares that depend on external modules? Do they have to be modules so I can import the requires modules?
I'd love some help, thanks!
You shiouldn't need to re-add AuthMiddleware to the AppModule's providers. It already exists in AuthModule. Also, you can bind the middleware inside the AuthModule if you want instead of in the AppModule and it will have the same global scope.

Nest.js this not working in constructor super

I try add configService to JwtStrategy:
constructor(readonly configService: ConfigService) {
super({
//...
secretOrKey: this.configService.get('SECRET_KEY'),
});
}
I'm using this instruction. But TS return me error:
'super' must be called before accessing 'this' in the constructor of a
derived class.
When I remove this (like in this answer), then Nest return another error:
Nest can't resolve dependencies of the JwtStrategy (?). Please make
sure that the argument ConfigService at index [0] is available in the
AuthModule context.
I fix it by adding ConfigService to providers in auth.module.ts file:
#Module({
controllers: [AuthController],
providers: [AuthService, JwtStrategy, ConfigService],
exports: [JwtStrategy],
})
I had to remove private from constructor and remove this from configService.

exporting nest js middleware to another project

I'm trying to export a custom middleware project in NestJS to all my other projects(and import this in all of them). My actual class is acl-jwt.middleware.ts in its bootstrap src folder.
In the acl-jwt.middleware.ts I have:
import { Injectable, NestMiddleware, } from '#nestjs/common';
#Injectable()
export class AclJwtMiddleware implements NestMiddleware {
use(req: any, res: any, next: () => void) {
console.log("ACL JWT Middleware !!")
next();
}
}
and my app.module.ts has:
import { Module, NestModule, MiddlewareConsumer, RequestMethod } from '#nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AclJwtMiddleware } from './acl-jwt.middleware';
#Module({
imports: [],
controllers: [AppController],
providers: [AppService],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(AclJwtMiddleware).forRoutes({ path: '*', method: RequestMethod.ALL });
}
}
And in my another project's app.module.ts, I'm importing this like the following
import { AclJwtMiddleware } from 'mi';
#Module({
imports: [],
controllers: [AppController],
providers: [AppService],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(AclJwtMiddleware).forRoutes({ path: '*', method: RequestMethod.ALL });
}
}
mi is my hosted package.
And then when I run my second project, I get the following error:
src/app.module.ts:16:34 - error TS2307: Cannot find module 'mi' or its corresponding type declarations.
16 import { AclJwtMiddleware } from 'mi';
Am I not exporting something? Or am I not importing it properly?
I've been searching all over the internet but I couldn't find something with my use case. Any help would be really good. Thank you all! :)
You'd need to make sure that in your package.json of your mi package, you have either main or files that points to the properly exported file/directory. If it is a barrel file, like index.js, then you need to make sure it exports the middleware properly.

Can't use custom provider

I'm trying to inject a custom provider as per the documentation:
https://docs.nestjs.com/fundamentals/custom-providers
My service:
#Injectable({scope: Scope.REQUEST})
export class ReportService implements OnModuleInit {
private readonly reportRepository: Repository<Report>;
constructor(
public config: ConfigService,
private readonly moduleRef: ModuleRef,
#Inject('CONNECTION') connection: Connection,
) {
console.log(connection);
}
...
app.module.ts:
const connectionProvider = {
provide: 'CONNECTION',
useValue: connection,
};
#Module({
imports: [
ReportModule,
...
],
providers: [connectionProvider],
controllers: [AppController],
})
export class AppModule implements NestModule {
Doing so results in:
Error: Nest can't resolve dependencies of the ReportService (ConfigService, ModuleRef, ?). Please make sure that the argument at index [2] is available in the ReportModule context.
What am I missing?
If a provider should be available outside of the module you defined it in, you need to add it to exports in the module definition (app.module). The other module (report.module) using it needs to add the module to its imports definition.
app.module.ts
const connectionProvider = {
provide: 'CONNECTION',
useValue: Connection,
};
#Module({
imports: [
ReportModule,
...
],
providers: [connectionProvider],
exports: ['CONNECTION'],
controllers: [AppController],
})
export class AppModule implements NestModule {}
report.module.ts
#Module({
imports: [
AppModule
],
providers: [],
controllers: [],
})
export class ReportModule implements NestModule {}
In your case, this produces a circular dependency which needs to be resolved.
Since app.module seems to be your core module you could make it global but you still need to export the provider.
Alternatively, I found it to be a good practice to not define any providers in app.module and use DynamicModule (e.g. forRoot and forFeature static initiator functions) to only instantiate what is needed, but that seem to be outside of this question.

How to resolve DI issue in nest.js?

I wanna understand how to import 3rd party library in nestjs through DI. So, i have a class AuthService:
export class AuthService {
constructor(
#Inject(constants.JWT) private jsonWebToken: any,
){}
....
}
JWT provider:
import * as jwt from 'jsonwebtoken';
import {Module} from '#nestjs/common';
import constants from '../../../constants';
const jwtProvider = {
provide: constants.JWT,
useValue: jwt,
};
#Module({
components: [jwtProvider],
})
export class JWTProvider {}
Libraries module:
import { Module } from '#nestjs/common';
import {BcryptProvider} from './bcrypt/bcrypt.provider';
import {JWTProvider} from './jsonwebtoken/jwt.provider';
#Module({
components: [
BcryptProvider,
JWTProvider,
],
controllers: [],
exports: [
BcryptProvider,
JWTProvider,
],
})
export class LibrariesModule{
}
I'm getting this error:
Error: Nest can't resolve dependencies of the AuthService (?). Please verify whether [0] argument is available in the current context.
at Injector.<anonymous> (D:\Learning\nest\project\node_modules\#nestjs\core\injector\injector.js:156:23)
at Generator.next (<anonymous>)
at fulfilled (D:\Learning\nest\project\node_modules\#nestjs\core\injector\injector.js:4:58)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
Besides, I wanna hear some recommendations about not using type any in the jsonWebToken variable.
The devil is in details. You can "import" other module into AuthModule like so:
#Module({
modules: [LibrariesModule], // <= added this line
components: [AuthService, JwtStrategy],
controllers: [],
})
export class AuthModule {
}
Source: here
Second question is still opened.

Resources