MikroORM

This recipe is here to help users getting started with MikroORM in Nest. MikroORM is the TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. It is a great alternative to TypeORM and migration from TypeORM should be fairly easy. The complete documentation on MikroORM can be found here.

info info @mikro-orm/nestjs is a third party package and is not managed by the NestJS core team. Please, report any issues found with the library in the appropriate repository.

Installation

Easiest way to integrate MikroORM to Nest is via @mikro-orm/nestjs module. Simply install it next to Nest, MikroORM and underlying driver:

  1. $ npm i @mikro-orm/core @mikro-orm/nestjs @mikro-orm/mysql # for mysql/mariadb

MikroORM also supports postgres, sqlite, and mongo. See the official docs for all drivers.

Once the installation process is completed, we can import the MikroOrmModule into the root AppModule.

  1. @Module({
  2. imports: [
  3. MikroOrmModule.forRoot({
  4. entities: ['./dist/entities'],
  5. entitiesTs: ['./src/entities'],
  6. dbName: 'my-db-name.sqlite3',
  7. type: 'sqlite',
  8. }),
  9. ],
  10. controllers: [AppController],
  11. providers: [AppService],
  12. })
  13. export class AppModule {}

The forRoot() method accepts the same configuration object as init() from the MikroORM package. Check this page for the complete configuration documentation.

Alternatively we can configure the CLI by creating a configuration file mikro-orm.config.ts and then call the forRoot() without any arguments. This won’t work when you use a build tools that use tree shaking.

  1. @Module({
  2. imports: [
  3. MikroOrmModule.forRoot(),
  4. ],
  5. ...
  6. })
  7. export class AppModule {}

Afterward, the EntityManager will be available to inject across entire project (without importing any module elsewhere).

  1. import { MikroORM } from '@mikro-orm/core';
  2. // Import EntityManager from your driver package or `@mikro-orm/knex`
  3. import { EntityManager } from '@mikro-orm/mysql';
  4. @Injectable()
  5. export class MyService {
  6. constructor(
  7. private readonly orm: MikroORM,
  8. private readonly em: EntityManager,
  9. ) {}
  10. }

info info Notice that the EntityManager is imported from the @mikro-orm/driver package, where driver is mysql, sqlite, postgres or what driver you are using. In case you have @mikro-orm/knex installed as a dependency, you can also import the EntityManager from there.

Repositories

MikroORM supports the repository design pattern. For every entity we can create a repository. Read the complete documentation on repositories here. To define which repositories should be registered in the current scope you can use the forFeature() method. For example, in this way:

info info You should not register your base entities via forFeature(), as there are no repositories for those. On the other hand, base entities need to be part of the list in forRoot() (or in the ORM config in general).

  1. // photo.module.ts
  2. @Module({
  3. imports: [MikroOrmModule.forFeature([Photo])],
  4. providers: [PhotoService],
  5. controllers: [PhotoController],
  6. })
  7. export class PhotoModule {}

and import it into the root AppModule:

  1. // app.module.ts
  2. @Module({
  3. imports: [MikroOrmModule.forRoot(...), PhotoModule],
  4. })
  5. export class AppModule {}

In this way we can inject the PhotoRepository to the PhotoService using the @InjectRepository() decorator:

  1. @Injectable()
  2. export class PhotoService {
  3. constructor(
  4. @InjectRepository(Photo)
  5. private readonly photoRepository: EntityRepository<Photo>,
  6. ) {}
  7. }

Using custom repositories

When using custom repositories, we can get around the need for @InjectRepository() decorator by naming our repositories the same way as getRepositoryToken() method do:

  1. export const getRepositoryToken = <T>(entity: EntityName<T>) =>
  2. `${Utils.className(entity)}Repository`;

In other words, as long as we name the repository same was as the entity is called, appending Repository suffix, the repository will be registered automatically in the Nest DI container.

  1. // `**./author.entity.ts**`
  2. @Entity()
  3. export class Author {
  4. // to allow inference in `em.getRepository()`
  5. [EntityRepositoryType]?: AuthorRepository;
  6. }
  7. // `**./author.repository.ts**`
  8. @Repository(Author)
  9. export class AuthorRepository extends EntityRepository<Author> {
  10. // your custom methods...
  11. }

As the custom repository name is the same as what getRepositoryToken() would return, we do not need the @InjectRepository() decorator anymore:

  1. @Injectable()
  2. export class MyService {
  3. constructor(private readonly repo: AuthorRepository) {}
  4. }

Load entities automatically

info info autoLoadEntities option was added in v4.1.0

Manually adding entities to the entities array of the connection options can be tedious. In addition, referencing entities from the root module breaks application domain boundaries and causes leaking implementation details to other parts of the application. To solve this issue, static glob paths can be used.

Note, however, that glob paths are not supported by webpack, so if you are building your application within a monorepo, you won’t be able to use them. To address this issue, an alternative solution is provided. To automatically load entities, set the autoLoadEntities property of the configuration object (passed into the forRoot() method) to true, as shown below:

  1. @Module({
  2. imports: [
  3. MikroOrmModule.forRoot({
  4. ...
  5. autoLoadEntities: true,
  6. }),
  7. ],
  8. })
  9. export class AppModule {}

With that option specified, every entity registered through the forFeature() method will be automatically added to the entities array of the configuration object.

info info Note that entities that aren’t registered through the forFeature() method, but are only referenced from the entity (via a relationship), won’t be included by way of the autoLoadEntities setting.

info info Using autoLoadEntities also has no effect on the MikroORM CLI - for that we still need CLI config with the full list of entities. On the other hand, we can use globs there, as the CLI won’t go thru webpack.

Request scoped handlers in queues

info info @UseRequestContext() decorator was added in v4.1.0

As mentioned in the docs, we need a clean state for each request. That is handled automatically thanks to the RequestContext helper registered via middleware.

But middlewares are executed only for regular HTTP request handles, what if we need a request scoped method outside of that? One example of that is queue handlers or scheduled tasks.

We can use the @UseRequestContext() decorator. It requires you to first inject the MikroORM instance to current context, it will be then used to create the context for you. Under the hood, the decorator will register new request context for your method and execute it inside the context.

  1. @Injectable()
  2. export class MyService {
  3. constructor(private readonly orm: MikroORM) {}
  4. @UseRequestContext()
  5. async doSomething() {
  6. // this will be executed in a separate context
  7. }
  8. }

Using AsyncLocalStorage for request context

By default, the domain api is used in the RequestContext helper. Since @mikro-orm/core@4.0.3, you can use the new AsyncLocalStorage too, if you are on up to date node version:

  1. // create new (global) storage instance
  2. const storage = new AsyncLocalStorage<EntityManager>();
  3. @Module({
  4. imports: [
  5. MikroOrmModule.forRoot({
  6. // ...
  7. registerRequestContext: false, // disable automatatic middleware
  8. context: () => storage.getStore(), // use our AsyncLocalStorage instance
  9. }),
  10. ],
  11. controllers: [AppController],
  12. providers: [AppService],
  13. })
  14. export class AppModule {}
  15. // register the request context middleware
  16. const app = await NestFactory.create(AppModule, { ... });
  17. app.use((req, res, next) => {
  18. storage.run(orm.em.fork(true, true), next);
  19. });

Testing

The @mikro-orm/nestjs package exposes getRepositoryToken() function that returns prepared token based on a given entity to allow mocking the repository.

  1. @Module({
  2. providers: [
  3. PhotoService,
  4. {
  5. provide: getRepositoryToken(Photo),
  6. useValue: mockedRepository,
  7. },
  8. ],
  9. })
  10. export class PhotoModule {}

Example

A real world example of NestJS with MikroORM can be found here