Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add InjectMikroORMs inject decorator #192

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,17 @@ export class PhotoService {
}
```

You can use the `@InjectMikroORMs` decorator to get all registered MikroORM instances:

```typescript
@Injectable()
export class MyService {

constructor(@InjectMikroORMs() private readonly orms: MikroORM[]) { }

}
```

## Testing

The `nestjs-mikro-orm` package exposes `getRepositoryToken()` function that returns prepared token based on a given entity to allow mocking the repository.
Expand Down
7 changes: 7 additions & 0 deletions src/mikro-orm.common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,13 @@ export const getMikroORMToken = (name: string) => `${name}_MikroORM`;
*/
export const InjectMikroORM = (name: string) => Inject(getMikroORMToken(name));

/**
* Injects the MikroORMs provider.
*
* @returns A decorator which will cause NestJS to inject the MikroORMs provider.
*/
export const InjectMikroORMs = () => Inject('MikroORMs');

/**
* Gets the injection token based on context name for the relevant EntityManager provider.
* @param name The context name of the database connection.
Expand Down
5 changes: 3 additions & 2 deletions src/multiple-mikro-orm.middleware.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { RequestContext, type MikroORM } from '@mikro-orm/core';
import { Inject, Injectable, type NestMiddleware } from '@nestjs/common';
import { Injectable, type NestMiddleware } from '@nestjs/common';
import { InjectMikroORMs } from './mikro-orm.common';

@Injectable()
export class MultipleMikroOrmMiddleware implements NestMiddleware {

constructor(@Inject('MikroORMs') private readonly orm: MikroORM[]) {}
constructor(@InjectMikroORMs() private readonly orm: MikroORM[]) {}

use(req: unknown, res: unknown, next: (...args: any[]) => void) {
RequestContext.create(this.orm.map(orm => orm.em), next);
Expand Down