Nest can't resolve dependencies of the ICommandBusAdapter - nestjs

Trying to use my ICommandBusAdapter.ts in my CreateUserAction.ts, but I get the following error:
[ExceptionHandler] Nest can't resolve dependencies of the ICommandBusAdapter (?). Please make sure that the argument at index [0] is available in the AdapterModule context
I have created a AdapterModule that will share all providers to others modules, but it doesn't seems work.
Any idea ?
AppModule.ts
import { UserModule } from './User/UserModule';
import { AdapterModule } from './Common/AdapterModule';
#Module({
imports: [AdapterModule, UserModule, // ...],
})
export class AppModule {}
AdapterModule.ts
import { CommandBusAdapter } from 'src/Infrastructure/Adapter/Bus/CommandBusAdapter';
const providers = [
{ provide: 'ICommandBusAdapter', useClass: CommandBusAdapter },
// ...
];
#Module({
providers: [...providers],
exports: [...providers],
})
export class AdapterModule {}
UserModule.ts
import { Module } from '#nestjs/common';
import { CreateUserAction } from 'src/Infrastructure/Action/User/CreateUserAction';
#Module({
controllers: [CreateUserAction],
})
export class UserModule {}
CommandBusAdapter.ts
import { CommandBus, ICommand } from '#nestjs/cqrs';
import { ICommandBusAdapter } from 'src/Application/Adapter/Bus/ICommandBusAdapter';
#Injectable()
export class CommandBusAdapter implements ICommandBusAdapter {
constructor(private readonly commandBus: CommandBus) {}
execute = (command: ICommand) => {
return this.commandBus.execute(command);
};
}
CreateUserAction.ts
import { ICommandBusAdapter } from 'src/Application/Adapter/Bus/ICommandBusAdapter';
export class CreateUserAction {
constructor(
#Inject('ICommandBusAdapter')
private readonly commandBus: ICommandBusAdapter,
) {}
// ...

Did you remember to add the CqrsModule to your application?
import { CqrsModule } from '#nestjs/cqrs';
#Module({
imports: [CqrsModule]
....
Without it there won't anything providing the CommandBus which you're trying to inject.
You can see an example here:
https://github.com/kamilmysliwiec/nest-cqrs-example/blob/master/src/heroes/heroes.module.ts

Related

Cannot inject custom provider for dynamic module

I tried to create a dynamic module PermissionModule like the following:
permTestApp.module.ts
#Module({
imports: [PermissionModule.forRoot({ text: 'abc' })],
providers: [],
controllers: [PermissionTestController],
})
export class PermissionTestAppModule {}
permission.module.ts
import { DynamicModule, Module } from '#nestjs/common'
import { PermissionGuard } from './guard/permission.guard'
#Module({})
export class PermissionModule {
public static forRoot(config: { text: string }): DynamicModule {
return {
module: PermissionModule,
providers: [
{
provide: 'xoxo',
useValue: config.text,
},
PermissionGuard,
],
exports: [PermissionGuard],
}
}
}
permission.guard.ts
import {
CanActivate,
ExecutionContext,
Inject,
Injectable,
} from '#nestjs/common'
#Injectable()
export class PermissionGuard implements CanActivate {
constructor(#Inject('xoxo') private readonly config: string) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
console.log(31, this.config)
return true
}
}
AFAIK, 'abc' string must be injected when PermissionGuard is used.
I tried to test it with the following code.
permission.e2e.spec.ts
beforeAll(async () => {
const moduleRef: TestingModule = await Test.createTestingModule({
imports: [PermissionTestAppModule],
})
.compile()
app = moduleRef.createNestApplication()
controller = await moduleRef.resolve(PermissionTestController)
await app.init()
})
but it says,
Nest can't resolve dependencies of the PermissionGuard (?). Please make sure that the argument xoxo at index [0] is available in the PermissionTestAppModule context.
Potential solutions:
- Is PermissionTestAppModule a valid NestJS module?
- If xoxo is a provider, is it part of the current PermissionTestAppModule?
- If xoxo is exported from a separate #Module, is that module imported within PermissionTestAppModule?
#Module({
imports: [ /* the Module containing xoxo */ ]
})
What am I doing wrong?

Trying to use in Nestjs Custom Repository typeorm

by example:
[https://stackoverflow.com/questions/72549668/how-to-do-custom-repository-using-typeorm-mongodb-in-nestjs][1]
Created custom repository в yandex-ndd-api-client.module:
import { DataSource, Repository } from 'typeorm';
import { Injectable } from '#nestjs/common';
// import {Team} from '#Domain/Team/Models/team.entity';
import { TestRepositoryTypeorm } from '../entity/testRepositoryTypeorm.entity';
#Injectable()
export class TestRepository extends Repository<TestRepositoryTypeorm> {
constructor(private dataSource: DataSource) {
super(TestRepositoryTypeorm, dataSource.createEntityManager());
}
async findTest(): Promise<any> { //TestRepositoryTypeorm | undefined
const findTests = await this.dataSource
.getRepository(TestRepositoryTypeorm)
.createQueryBuilder('test')
.getMany();
return await findTests;
}
}
Connected in the module::
providers: [YandexDeliveryService, YandexNddApiClientService, ConfigService, SyncService, TestRepository],
Connected it to the service yandex-ndd-api-client.service:
import { TestRepository } from './repository/testRepositoryTypeorm.retository';
#Injectable()
export class YandexNddApiClientService {
constructor(
// private yandexDeliveryApiService: YandexDeliveryApiService,
private httpService: HttpService,
private dataSource: DataSource,
private configService: ConfigService,
#Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger,
// #InjectRepository(TestRepository)
private testRepository: TestRepository,
) {}
Called in service:
//testRepositoryTypeorm
async testRepositoryTypeorm(): Promise<any> {
try {
console.log('testRepositoryTypeorm');
// return 'testRepositoryTypeorm';
return await this.testRepository.findTest();
} catch (e) {
console.log('ERROR testRepositoryTypeorm:', e);
}
}
As a result:
ERROR [ExceptionHandler] Nest can't resolve dependencies of the YandexNddApiClientService (HttpService, DataSource, ConfigService, winston, ?, SchedulerRegistry). Please make sure that the argument TestRepository at index [4] is available in the DetmirApiClientModule context.
Potential solutions:
- If TestRepository is a provider, is it part of the current DetmirApiClientModule?
- If TestRepository is exported from a separate #Module, is that module imported within DetmirApiClientModule?
#Module({
imports: [ /* the Module containing TestRepository */ ]
})
[1]: https://stackoverflow.com/questions/72549668/how-to-do-custom-repository-using-typeorm-mongodb-in-nestjs
DetmirApiClientModule.ts:
import { Module } from '#nestjs/common';
import { DetmirApiClientService } from './detmir-api-client.service';
import { DetmirApiClientController } from './detmir-api-client.controller';
import { SyncService } from 'src/sync.service';
import { YandexNddApiClientService } from 'src/yandex-ndd-api-client/yandex-ndd-api-client.service';
import { HttpModule, HttpService } from '#nestjs/axios';
import { WINSTON_MODULE_PROVIDER } from 'nest-winston';
import { YandexNddApiClientModule } from 'src/yandex-ndd-api-client/yandex-ndd-api-client.module';
#Module({
providers: [DetmirApiClientService, SyncService, YandexNddApiClientService],
controllers: [DetmirApiClientController],
imports: [HttpModule, YandexNddApiClientModule], //TestRepository
})
export class DetmirApiClientModule {}
Most likely your YandexNddApiClientModule does not add the YandexNddApiClientService to the exports array. Add YandexNddApiClientService to the exports if it is not already there and remove YandexNddApiClientService from the providers array of DetmirApiClientModule. The error is being raised because you have YandexNddApiClientService declared in the providers of DetmirApiClientModule so Nest is trying to create the provider in the new module rather than re-use the module from its original context

NestJS - Nest can't resolve dependencies of the ConfigurationService (ConfigService, ?)

I am new to NestJs + Typescript, trying to initialize a project, after building it throws the following error:
ERROR [ExceptionHandler] Nest can't resolve dependencies of the ConfigurationService (ConfigService, ?). Please make sure that the argument CachingService at index [1] is available in the ConfigurationService context.
I tried many possible ways to solve this but no luck yet
These are the two modules in question:
import { CacheModule, Module } from '#nestjs/common';
import { CachingService } from './caching.service';
#Module({
imports: [
CacheModule.register({
ttl: 0,
}),
],
providers: [CachingService],
exports: [CachingService],
})
export class CachingModule {}
import { Module } from '#nestjs/common';
import { ConfigModule } from '#nestjs/config';
import { CachingModule } from '../caching/caching.module';
import { ConfigurationService } from './configuration.service';
import { config } from './environmentConfig/default.config';
import deploymentConfig from './deploymentConfig/config';
import { CachingService } from '../caching/caching.service';
#Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
load: [() => config, deploymentConfig],
}),
CachingModule,
],
providers: [ConfigurationService, CachingService],
exports: [ConfigurationService],
})
export class ConfigurationModule {}
This is the service where I am trying to use the cachingModule and the error is being thrown:
import { Injectable, Logger, OnModuleInit } from '#nestjs/common';
import { ConfigService } from '#nestjs/config';
import { CachingService } from '../caching/caching.service';
#Injectable()
export class ConfigurationService implements OnModuleInit {
private readonly logger = new Logger(ConfigurationService.name);
constructor(
private readonly configService: ConfigService,
private cachingService: CachingService,
) {}
How to fix this?
Remove the CachingService as a provider in the ConfigurationModule.

NestJs error: can't resolve dependencies of the Service (?). Please make sure that the argument SchemaModel at index [0] is available

I get this error:
Nest can't resolve dependencies of the UserPreferencesService (?). Please make sure that the argument UserPreferencesSchemaModel at index [0] is available in the UserPreferencesModule context.
What can the error be? I understand that the problem happens in the user-preferences.service.ts file. as when I comment the following lines from the user-preferences.module.ts file all works fine.
controllers: [UserPreferencesController],
providers: [UserPreferencesService],
This is my user-preferences.service.ts file:
import { Injectable } from '#nestjs/common';
import { Model } from 'mongoose';
import { InjectModel } from '#nestjs/mongoose';
import { UserPreferencesInterface } from './interfaces/user-preferences.interface';
#Injectable()
export class UserPreferencesService {
constructor(
#InjectModel('UserPreferencesSchema')
private readonly UserPreferencesModel: Model<UserPreferencesInterface>,
) {}
public async postUserPreferences(newUserPreferences: any): Promise<any> {
const userPreferences = await new this.UserPreferencesModel(
newUserPreferences,
);
return userPreferences.save();
}
}
app.module.ts
import { Module } from '#nestjs/common';
import { UserPreferencesModule } from './user-preferences/user-preferences.module';
import { MongooseModule } from '#nestjs/mongoose';
#Module({
imports: [
UserPreferencesModule,
MongooseModule.forRoot(
'mongodb+srv://user:pass#db.hucjifz.mongodb.net/dbname?retryWrites=true&w=majority',
),
],
})
export class AppModule {}
user-preferences.module.ts
import { Module } from '#nestjs/common';
import { MongooseModule } from '#nestjs/mongoose';
import { UserPreferencesSchema } from './schemas/user-preferences.schema';
import { UserPreferencesController } from './user-preferences.controller';
import { UserPreferencesService } from './user-preferences.service';
#Module({
imports: [
MongooseModule.forFeature([
{
name: 'UserPreferences',
schema: UserPreferencesSchema,
},
]),
],
controllers: [UserPreferencesController],
providers: [UserPreferencesService],
})
export class UserPreferencesModule {}
user-preferences.controller.ts
import {Body, Controller, Get, Post, Put } from '#nestjs/common';
import { UserPreferencesService } from './user-preferences.service';
import { UserPreferencesDto } from './dto/user-preferences.dto'
#Controller('user-preferences')
export class UserPreferencesController {
constructor(private userPreferencesService: UserPreferencesService) {}
#Get()
public getUserPreferences() {
return this.userPreferencesService.getUserPreferences();
}
#Post ()
public postUserPreferences(
#Body() userPreferences: UserPreferencesDto
) {
return this.userPreferencesService.postUserPreferences( userPreferences );
}
}
this is the complete error:
[Nest] 65481 - 06/07/2022, 6:00:04 AM ERROR [ExceptionHandler] Nest can't resolve dependencies of the UserPreferencesService (?). Please make sure that the argument UserPreferencesSchemaModel at index [0] is available in the UserPreferencesModule context.
Potential solutions:
- If UserPreferencesSchemaModel is a provider, is it part of the current UserPreferencesModule?
- If UserPreferencesSchemaModel is exported from a separate #Module, is that module imported within UserPreferencesModule?
#Module({
imports: [ /* the Module containing UserPreferencesSchemaModel */ ]
})
Error: Nest can't resolve dependencies of the UserPreferencesService (?). Please make sure that the argument UserPreferencesSchemaModel at index [0] is available in the UserPreferencesModule context.
Potential solutions:
- If UserPreferencesSchemaModel is a provider, is it part of the current UserPreferencesModule?
- If UserPreferencesSchemaModel is exported from a separate #Module, is that module imported within UserPreferencesModule?
#Module({
imports: [ /* the Module containing UserPreferencesSchemaModel */ ]
})
at Injector.lookupComponentInParentModules (/Users/davids/Developmet/nestjs/sync-user-preferences/node_modules/#nestjs/core/injector/injector.js:231:19)
at Injector.resolveComponentInstance (/Users/davids/Developmet/nestjs/sync-user-preferences/node_modules/#nestjs/core/injector/injector.js:184:33)
at resolveParam (/Users/davids/Developmet/nestjs/sync-user-preferences/node_modules/#nestjs/core/injector/injector.js:106:38)
at async Promise.all (index 0)
at Injector.resolveConstructorParams (/Users/davids/Developmet/nestjs/sync-user-preferences/node_modules/#nestjs/core/injector/injector.js:121:27)
at Injector.loadInstance (/Users/davids/Developmet/nestjs/sync-user-preferences/node_modules/#nestjs/core/injector/injector.js:52:9)
at Injector.loadProvider (/Users/davids/Developmet/nestjs/sync-user-preferences/node_modules/#nestjs/core/injector/injector.js:74:9)
at async Promise.all (index 3)
at InstanceLoader.createInstancesOfProviders (/Users/davids/Developmet/nestjs/sync-user-preferences/node_modules/#nestjs/core/injector/instance-loader.js:44:9)
at /Users/davids/Developmet/nestjs/sync-user-preferences/node_modules/#nestjs/core/injector/instance-loader.js:29:13
O.K, after digging alot I found that the problem was caused because MongooseModule.forFeature name and #InjectModel() in user-preferences.service.ts value were not identical.
They must be identical.

How do I include a request scoped provider which needs an injected request in via an imported module

We are building up a mono-repo of microservices, and want to have some shared libraries which we import into various services.
Right now I am trying to build up a shared module which will have a provider which needs access to the request. Here is an example:
import { Injectable, Scope, Inject } from '#nestjs/common'
import { REQUEST } from '#nestjs/core'
import { Request } from 'express'
import { APILogger } from '#freebird/logger'
import { APIGatewayProxyEvent, Context } from 'aws-lambda'
export interface IAPIGatewayRequest extends Request {
apiGateway?: {
event?: APIGatewayProxyEvent
context?: Context
}
}
#Injectable({ scope: Scope.REQUEST })
export class RequestLogger extends APILogger {
constructor(#Inject(REQUEST) request: IAPIGatewayRequest) {
if (!request.apiGateway || !request.apiGateway.event || !request.apiGateway.context) {
throw new Error(
'You are trying to use the API Gateway logger without having used the aws-serverless-express middleware',
)
}
super(request.apiGateway.event, request.apiGateway.context)
}
}
I have been trying to bundle this as a module like so:
import { Module } from '#nestjs/common'
import { RequestLogger } from './logger'
#Module({
providers: [RequestLogger],
exports: [RequestLogger],
})
export class LambdaModule {}
And then import it into the main service module like this:
import { Module } from '#nestjs/common'
import { AppController } from './app.controller'
import { AppService } from './app.service'
import { LambdaModule } from '#freebird/nest-lambda'
#Module({
imports: [LambdaModule],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
However, when I do this I get an error:
Nest can't resolve dependencies of the RequestLogger (?). Please make
sure that the argument at index [0] is available in the AppModule
context.
But when I pull the RequestLogger provider into the service module, and include it like this I get no errors:
import { Module } from '#nestjs/common'
import { AppController } from './app.controller'
import { AppService } from './app.service'
import { RequestLogger } from './logger'
#Module({
controllers: [AppController],
providers: [AppService, RequestLogger],
})
export class AppModule {}
I discovered the problem. In my case I had slightly different requirements between my library package and the service package. So different versions of nest were in play. This apparently causes conflicts.

Resources