How to fix AXIOS_INSTANCE_TOKEN at index [0] is available in the Module context - node.js

I am using Axios in my project to call some third-party endpoints. I don't seem to understand the
error
Nest can't resolve dependencies of the HttpService (?). Please make sure that the argument
AXIOS_INSTANCE_TOKEN at index [0] is available in the TimeModule context.
Potential solutions:
- If AXIOS_INSTANCE_TOKEN is a provider, is it part of the current TimeModule?
- If AXIOS_INSTANCE_TOKEN is exported from a separate #Module, is that module imported within TimeModule?
#Module({
imports: [ /* the Module containing AXIOS_INSTANCE_TOKEN */ ]
})
This is the module
#Module({
imports: [TerminalModule,],
providers: [TimeService, HttpService],
controllers: [TimeController]
})
export class TimeModule { }
This is the service
#Injectable()
export class TimeService {
constructor(private httpService: HttpService,
#InjectModel('PayMobileAirtime') private time: Model<Time>,
#Inject(REQUEST) private request: any,
) { }
This is an example of one of my get and post methods
async PrimeAirtimeProductList(telcotime: string) {
let auth = await this.TimeAuth()
const productList = await this.httpService.get(`https://clients.time.com/api/top/info/${telcotime}`,
{
headers: {
'Authorization': `Bearer ${auth.token}`
}
}
).toPromise();
return productList.data
}
Post
const dataToken = await this.manageTimeAuth()
const url = `https://clients.time.com/api/dataup/exec/${number}`
const BuyTelcoData = await this.httpService.post(url, {
"product_id": product_id,
"denomination": amount,
"customer_reference": reference_id
}, {
headers: {
'Authorization': `Bearer ${dataToken.token}`
}
}).toPromise();
const data = BuyTelcoData.data;

Import HttpModule from #nestjs/common in TimeModule and add it to the imports array.
Remove HttpService from the providers array in TimeModule. You can directly import it in the TimeService.
import { HttpModule } from '#nestjs/common';
...
#Module({
imports: [TerminalModule, HttpModule],
providers: [TimeService],
...
})
TimeService:
import { HttpService } from '#nestjs/common';
If your response type is an Observable of type AxiosResponse, then import these two as well in the service file TimeService.
import { Observable } from 'rxjs';
import { AxiosResponse } from 'axios';
For reference, check out http-module and this post.

Don't pass HttpService in the providers. Import only HttpModule.

Related

NestJS : ERROR [ExceptionHandler] Nest can't resolve dependencies of the ClientService

I am working with NestJSproject. I make an entity Client and a DTO for the "inscrit()" function
when I ran the project, I got the following:
ERROR [ExceptionHandler] Nest can't resolve dependencies of the ClientService (?). Please make sure that the argument ClientRepository at index [0] is available in the ClientModule context.
Potential solutions:
- If ClientRepository is a provider, is it part of the current ClientModule?
- If ClientRepository is exported from a separate #Module, is that module imported within ClientModule?
#Module({
imports: [ /* the Module containing ClientRepository */ ]
})
this is the client.service.ts file
import { Injectable } from '#nestjs/common';
import { InjectRepository } from '#nestjs/typeorm';
import { Repository } from 'typeorm';
import { ClientInscritDto } from './dto/client-inscrit.dto';
import { Client } from './entity/client.entity';
import * as bcrypt from 'bcrypt';
import { ConflictException } from '#nestjs/common/exceptions';
#Injectable()
export class ClientService {
constructor(
#InjectRepository(Client)
private clientRepository : Repository<Client>
){}
async inscrit(clientData: ClientInscritDto) : Promise<Partial<Client>>{
const client = this.clientRepository.create({...clientData});
client.salt = await bcrypt.genSalt();
client.mdp = await bcrypt.hash(clientData.mdp, client.salt);
try{
await this.clientRepository.save(client);
}catch(err){
throw new ConflictException(`le surname ${clientData.surname} ou l'email ${clientData.email} existe déjà`);
}
return client;
}
}
The answer for this was that I forget adding in client.module.ts file:
imports: [
TypeOrmModule.forFeature([Client])
],

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?

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.

NestJS Unable to Resolve Dependencies

I'm getting this error when I run my NestJS app.
[Nest] 19139 - 03/01/2020, 2:10:01 PM [ExceptionHandler] Nest can't resolve dependencies of the AccountsService (AccountRepository, ?, HashPasswordService). Please make sure that the argument Object at index [1] is available in the AccountsModule context.
Potential solutions:
- If Object is a provider, is it part of the current AccountsModule?
- If Object is exported from a separate #Module, is that module imported within AccountsModule?
#Module({
imports: [ /* the Module containing Object */ ]
})
+1ms
I am a bit confused what it causing this. As far as I can tell, my code looks correct. Here is the definition for my AccountsService class:
import { Injectable, ConflictException, Logger, InternalServerErrorException, NotFoundException, Inject } from '#nestjs/common';
import { InjectRepository } from '#nestjs/typeorm';
import { Account } from 'src/accounts/entities/account';
import { Repository, FindManyOptions, UpdateDateColumn } from 'typeorm';
import { CreateAccount } from 'src/accounts/dtos/create-account';
import { GetAccountsWithFilters } from 'src/accounts/dtos/get-accounts-with-filters';
import { UpdateAccountProfileInfo } from 'src/accounts/dtos/update-account-profile-info';
import { HashPasswordService } from '../hash-password/hash-password.service';
import { UpdateEmail } from 'src/accounts/dtos/update-email';
import { UpdatePhone } from 'src/accounts/dtos/update-phone';
import { AccountRepository } from 'src/accounts/repositories/account-repository';
/**
* AccountsService encapsulates all the actions that can be performed by an account.
*/
#Injectable()
export class AccountsService {
constructor(
#InjectRepository(AccountRepository) private accountRepository: AccountRepository,
private logger = new Logger("Accounts Service"),
#Inject(HashPasswordService)
private hashPasswordService: HashPasswordService,
) { }
// more code here
}
My Module looks like this.
import { Module } from '#nestjs/common';
import { AccountsService } from './services/accounts/accounts.service';
import { TypeOrmModule } from '#nestjs/typeorm';
import { Account } from './entities/account';
import { AccountsController } from './controllers/accounts/accounts.controller';
import { AccountCleanerService } from './services/account-cleaner/account-cleaner.service';
import { AuthenticationService } from './services/authentication/authentication.service';
import { AuthenticationController } from './controllers/authentication/authentication.controller';
import { HashPasswordService } from './services/hash-password/hash-password.service';
import { JwtModule } from "#nestjs/jwt";
import { PassportModule } from "#nestjs/passport";
import { JwtStrategy } from './auth-strategies/jwt-strategy';
import { AccountRepository } from './repositories/account-repository';
#Module({
imports: [
TypeOrmModule.forFeature([
Account,
AccountRepository,
]),
JwtModule.register({
secret: "SOME_APP_SECRET",
signOptions: {
expiresIn: 3600
}
}),
PassportModule.register({
defaultStrategy: "jwt",
}),
],
controllers: [
AccountsController,
AuthenticationController,
],
providers: [
AccountRepository,
HashPasswordService,
AccountsService,
AccountCleanerService,
AuthenticationService,
JwtStrategy,
],
exports: [JwtStrategy, PassportModule],
})
export class AccountsModule { }
Lastly, here is the App Module:
import { Module } from '#nestjs/common';
import { AccountsModule } from './accounts/accounts.module';
import { TypeOrmModule } from "#nestjs/typeorm";
import {Account} from "./accounts/entities/account";
import { ConfigModule } from "#nestjs/config";
import account from "./../config/account";
import auth from "./../config/auth";
import database from "./../config/database";
import server from "./../config/server";
import { AccountRepository } from './accounts/repositories/account-repository';
#Module({
imports: [
AccountsModule,
ConfigModule.forRoot({
// make this module available globally
isGlobal: true,
// The configuration files.
load: [
account,
auth,
database,
server
],
}),
TypeOrmModule.forRoot({
type: "mongodb",
url: "my connection string here",
entities: []
}),
],
controllers: [],
providers: [],
})
export class AppModule { }
As you can see, I have clearly made the services available to the module. So, I am kind of confused why Nest is unable to resolve the dependencies. Additionally, there should not be any other module right now, aside from the App module.,, which is also provided above. Any ideas why NestJS is throwing this error?
Nest is having trouble resolving the dependency of Logger, and as it is not provided in the providers array, it won't be able to resolve it. You've got three options:
1) Move the private logger = new Logger('Account Service') to the body of the constructor
2) Move the private logger = new Logger('Account Service') to the third position and mark it as #Optional() so that Nest doesn't throw an error when the value is unknown.
3) Add Logger to the providers array of AccountModule and then use the this.logger.setContext() method to properly set the context
The built in Logger class is #Injectable() so it is possible to use it through DI, but you have to ensure that it is provided just as any other provider is in the NestJS ecosystem.

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