NestJS and Jest: Nest can't resolve dependencies of the UserService - jestjs

I am using a NestJS + MikroORM stack and trying to write tests using Jest.
On the user.service.spec.ts I am always getting the following error:
Nest can't resolve dependencies of the UserService (?). Please make sure that the argument UserRepository at index [0] is available in the RootTestModule context
The user.service.spec.ts:
describe('UserService', () => {
let userService: UserService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
UserService,
{
provide: getRepositoryToken(User),
useValue: {
find: jest.fn().mockResolvedValue([]),
findOneOrFail: jest.fn().mockResolvedValue({}),
create: jest.fn().mockReturnValue({}),
save: jest.fn(),
update: jest.fn().mockResolvedValue(true),
delete: jest.fn().mockResolvedValue(true),
},
},
],
}).compile();
userService = module.get<UserService>(UserService);
});
it('should be defined with dependencies', () => {
expect(userService).toBeDefined();
});
});
The user.repository.ts:
#Repository(User)
export class UserRepository extends EntityRepository<User> {}
Why would that be happening? According to all other tutorials, it should work. Thanks.

if your UserService's constructor has
private readonly repo: UserRepository
then you should use provide: UserRepository because now your provider's token is a class references, not its name.

Nest 8 changed the way DI works, it was using string tokens before, but now it uses class references instead. The nest MikroORM adapter does register both string token and class reference for custom repositories. Here you are registering the repository yourself, so you either need to register it both ways or at least the way you use.
Importing via the type requires the class reference way. Importing via #InjectRepository() requires the string token. forFeature() call registers them both in case the entity has a custom repository class.
https://github.com/mikro-orm/nestjs/blob/e51206762f9eb3e96bfc9edbb6abbf7ae8bc08a8/src/mikro-orm.providers.ts#L82-L94
So either add the provide: UserRepository as suggested in the other answer, or use #InjectRepository() decorator.

Related

How to exclude and include different middleware for different modules in nestjs?

I have two auth middleware in my nestjs project.
AdminAuth Middleware
UserAuth Middleware
AdminAuthMiddleware will be used in AdminModule while UserAuthMiddleware will be used in rest of the modules.
export class AppModule implements NestModule {
static register(option: DynamicModuleOptionType): DynamicModule {
return {
module: AppModule,
imports: [
BullQueueModule.register(option),
KafkaModule.register(option),
CronModule.register(option),
],
};
}
configure(consumer: MiddlewareConsumer) {
consumer.apply(CorsMiddleware).forRoutes('*');
consumer.apply(AdminAuthMiddleware).forRoutes('/v1/admin/(.*)');
consumer
.apply(UserAuthMiddleware)
.exclude(
'v1/admin/(.*)',
'/_livez',
'/_healthz',
'/_readyz',
'/swagger.json',
)
.forRoutes('*');
}
}
UserAuthMiddleware middleware is working correctly, but AdminAuthMiddleware is not registering for admin routes.
How can i solve this issue?. Any help will be highly appreciated.
I tried registering AdminAuthMiddleware in AdminModule only, it did not work.
Tried changing the sequence of middleware registration.your text

NX workspace NestJS - loading DTO classes from libraries

I have NestJS api in NX workspace.
I created library "model" with user.ts:
export interface User{
name: string
}
export interface UserDto extends User {
email: string
}
user.controller.ts:
import { UserDto } from "#project/model";
#Post()
async create(#Req() req, #Res() res, #Body() user: UserDto): Promise<string>{
}
I'm getting build error:
C:\app\project\node_modules#nrwl\node\src\executors\node\node-with-require-overrides.js:16
return originalLoader.apply(this, arguments);
^
Error [ERR_REQUIRE_ESM]: require() of ES Module C:\app\project\node_modules#angular\core\fesm2015\core.mjs not supported.
Instead change the require of C:\app\project\node_modules#angular\core\fesm2015\core.mjs to a dynamic import() which is available in all CommonJS modules.
But this works fine:
#Post()
async create(#Req() req, #Res() res): Promise<string>{
let user: UserDto = <UserDto>{};
}
When I created userDTO in NestJS project, it works. How to load entities or DTO from libraries to NestJS? Looks like the fault lies with the decorators.
Thanks

How to reference the app instance in a module in Nest.js

I'm working on a project that's using multiple Nest repos, around 4.
Every repo needs to implementing logging to log things like
Server lifecycle events
Uncaught errors
HTTP requests/responses
Ideally, I'd like to package everything up into a module which I can publish to my company's NPM organization and just consume directly in each of my projects.
That way, it would take very minimal code to get logging set up in each project.
One of the things I'd like to log in my server lifecycle event is the server's url.
I know you can get this via app.getUrl() in the bootstrapping phase, but it would be great to have access to the app instance in a module's lifecycle hook like so.
#Module({})
export class LoggingModule implements NestModule {
onApplicationBootstrap() {
console.log(`Server started on ${app.getUrl()}`)
}
beforeApplicationShutdown() {
console.log('shutting down')
}
onApplicationShutdown() {
console.log('successfully shut down')
}
configure(consumer: MiddlewareConsumer) {
consumer.apply(LoggingMiddleware).forRoutes('*')
}
}
Is this possible?
There's no way (besides hacky ones, maybe) to access the app itself inside modules.
As you can see here, app.getUrl() uses the underlying HTTP server. Thus I guess you can retrieve the same data using the provider HttpAdapterHost.
Ï thought I'd chime in and offer one of the hacky solutions. Only use this, if there is absolutely no other way or your deadline is coming in an hour.
Create a class that can hold the application instance
export class AppHost {
app: INesApplication
}
And a module to host it
#Module({
providers: [AppHost]
exports: [AppHost]
})
export class AppHostModule {}
In your bootstrap() function, retrieve the AppHost instance and assign the app itself
// after NestFactory.create() ...
app.select(AppHostModule).get(AppHost).app = app;
Now, the actual application will be available wherever you inject AppHost.
Be aware, though, that the app will not be available inside AppHost before the whole application bootstraps (in onModuleInit, onApplicationBootstrap hooks or in provider factories), but it should be available in shutdown hooks.
Not sure is that hacky... I'm using this to prevent the server from starting in case of pending migrations.
// AppModule.ts
export class AppModule implements NestModule {
app: INestApplication;
async configure(consumer: MiddlewareConsumer) {
if (await this.hasPendingMigrations()) {
setTimeout(()=> {
this.logger.error("There are pending migrations!")
process.exitCode = 1;
this.app.close();
}, 1000);
}
//...
}
public setApp(app: INestApplication) {
this.app = app;
}
//...
}
//main.ts
const app = await NestFactory.create(AppModule, {
logger: config.cfgServer.logger,
});
app.get(AppModule).setApp(app);

Nestjs wrapping external module in forRootAsync and inject instance

I've been developing a wrapper module for nestjs based on a nodejs module. I created a static forRoot method in order to get the configuration. I created such a prodiver within the forRoot method:
const MyProvider = {
provide: PROVIDER_TOKEN,
useValue: new MyClass(options),
};
I also export it, so in consumer module it's easy to inject it in order to access to all methods of nodejs module. Besides, I am able to wrap up all methods of that module into my service methods. So, the following code give me access to the main module's instance:
constructor(#Inject(PROVIDER_TOKEN) private readonly myClass: MyClass) {}
Then I decided to create a forRootAsync method that can handle getting configuration with useFactory. Now this is my provider in forRootAsync method:
const MyProvider= {
provide: PROVIDER_TOKEN,
useFactory: optionsAsync.useFactory,
inject: optionsAsync.inject || []
};
But this time if I inject PROVIDER_TOKEN to the service, this is simply the configuration object (that I pass from the consumer module). So I guess I should create the instance within constructor. Maybe something like this:
constructor(#Inject(PROVIDER_TOKEN) private readonly myClass) {
if(!this.myClass typeof MyClass) {
this.myClass = new MyClass(this.myClass);
}
}
By this, I can't access the instance of the main module in the consumer modules by injecting PROVIDER_TOKEN token. The goal is to access all methods of that module without having to wrap all the methods up. Any idea?
We should handle this with two providers. In the first one, we pass the factory provider as following:
{
provide: HTTP_MODULE_OPTIONS,
useFactory: options.useFactory,
inject: options.inject || [],
};
Then we create another provider which injects the first provider (which nestjs resolve the dependency at that point):
{
provide: AXIOS_INSTANCE_TOKEN,
useFactory: (config: HttpModuleOptions) => Axios.create(config),
inject: [HTTP_MODULE_OPTIONS],
},
Here is the example.

How to split Nest.js microservices into separate projects?

Let's say I want to create a simplistic cinema-management platform. It needs few microservices: movies, cinemas, payments, etc.
How would you go about doing it in Nest.js? I don't want them in the same big folder as that feels like making a monolith. I want them to be separate Nest.js projects with their own git repositories so I can orchestrate them with Kubernetes later on.
How? How to connect from service cinemas to service movies if they are two separate projects and only share, let's say, Redis?
Edit:
This is not a question about microservices in general. This is a question Nest.js specific. I read the documentation, I know there are decorators like #Client for connecting to the transport layer. I just want to know where to use that decorator and maybe see a short snippet of code on "having two separate Nest.js repositories how to connect them together so they can talk to each other".
I don't care about the transport layer, that thing I can figure out myself. I just need some advice on the framework itself as I believe the documentation is lacking.
I got it working. Basically the way to do it is to create two separate projects. Let's say - one is a createMicroservice and another is just an HTTP app (but could easily be another microservice). I used a "normal" app just so I can call it easily for testing.
Here is the main.ts file that creates microservice.
import { NestFactory } from '#nestjs/core';
import { AppModule } from './app.module';
import { Transport } from '#nestjs/common/enums/transport.enum';
async function bootstrap() {
const app = await NestFactory.createMicroservice(AppModule, {
transport: Transport.REDIS,
options: {
url: 'redis://localhost:6379',
},
});
await app.listen(() => console.log('MoviesService is running.'));
}
bootstrap();
And one of the controllers:
#Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
#MessagePattern({ cmd: 'LIST_MOVIES' })
listMovies(): string[] {
return ['Pulp Fiction', 'Blade Runner', 'Hatred'];
}
}
Now - in the microservice you declare to what kinds of events should controllers react to (#MessagePattern). While in the "normal" service you do this in the controller when you want to ask other microservices for something (the main.ts is the simplest example that you get when you create a new project using #nestjs/cli.
The controller code:
#Controller()
export class AppController {
private readonly client: ClientProxy;
constructor(private readonly appService: AppService) {
this.client = ClientProxyFactory.create({
transport: Transport.REDIS,
options: {
url: 'redis://localhost:6379',
},
});
}
#Get()
listMovies() {
const pattern = { cmd: 'LIST_MOVIES' };
return this.client.send<string[]>(pattern, []);
}
}
So as long a client is connected to the same transport layer as the microservice - they can talk to each other by using the #MessagePattern.
For nicer code you can move the this.client part from a constructor to a provider and then use dependency injection by declaring the provider in the module.

Resources