Skip to content

Commit

Permalink
feat: add InjectMikroORMs inject decorator (#192)
Browse files Browse the repository at this point in the history
  • Loading branch information
tsangste authored Jan 22, 2025
1 parent 4bb7a98 commit b734867
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
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

0 comments on commit b734867

Please sign in to comment.