Next.js prisma recipe - ERROR [ExceptionHandler] Nest can't resolve dependencies of the AppController (?, PostService) - nestjs

I followed the recipe on https://docs.nestjs.com/recipes/prisma (twice) and I get the following error:
ERROR [ExceptionHandler] Nest can't resolve dependencies of the AppController (?, PostService). Please make sure that the argument UserService at index [0] is available in the AppModule context.
when starting with npm start.
The only thing I have changed from the recipe is in the last block of code where I changed
import { PrismaService } from './services/prisma/prisma.service';
to
import { PrismaService } from './prisma.service';
beacause prisma.service isn't located at that location.
I don't know what to do to fix it. I would have expected a guide on the official site to work.

I changed app.module.ts into this:
import { Module } from '#nestjs/common';
import { AppController } from './app.controller';
import { UserService } from './user.service';
import { PostService } from './post.service';
import { PrismaService } from './prisma.service';
#Module({
imports: [],
controllers: [AppController],
providers: [UserService, PostService, PrismaService],
})
export class AppModule {}
Now it works.

Related

TypeError: Cannot read properties of undefined when call method of injected provider in NestJS

Follow tutorial at here, I'm just implement simple NestJS app with a module have injected provider below:
# app.module.ts
import { Module } from '#nestjs/common'
import { ConfigModule } from '#nestjs/config'
import { AuthModule } from '#/modules/auth/auth.module'
#Module({
imports: [
ConfigModule.forRoot(),
AuthModule
]
})
export class AppModule {}
# auth.module.ts
import { Module } from '#nestjs/common'
import { AuthController } from '#/modules/auth/auth.controller'
import { AuthService } from '#/modules/auth/auth.service'
#Module({
controllers: [AuthController],
providers: [AuthService]
})
export class AuthModule {}
# auth.controller.ts
import { Controller, Get } from '#nestjs/common'
import { AuthService } from '#/modules/auth/auth.service'
#Controller('auth')
export class AuthController {
constructor (private readonly service: AuthService) {}
#Get('me')
public getSelfInfo (): string {
return this.service.getSelfInfo()
}
}
# auth.service.ts
import { Injectable } from '#nestjs/common'
#Injectable()
export class AuthService {
getSelfInfo (): string {
return 'ok'
}
}
But when call to endpoint, this error thrown:
[Nest] 17196 - 09/23/2022, 2:34:18 PM ERROR [ExceptionsHandler] Cannot read properties of undefined (reading 'getSelfInfo')
TypeError: Cannot read properties of undefined (reading 'getSelfInfo')
at AuthController.getSelfInfo (/dist/modules/auth/auth.controller.js:16:29)
Please tell me which problem at here.
Solved this issue when add code block below to app.controller.ts:
#Inject(AuthService)
private readonly service: AuthService
constructor (service: AuthService) {
this.service = service
}

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.

Nest can't resolve dependencies of the ICommandBusAdapter

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

Resources