Design Patterns - Unit of Work Pattern in TypeScript using MikroORM

Before you look at the Unit of Work pattern example in TypeScript using MikroORM, you can see my post about what is the Unit of Work pattern.

Example of the Unit of Work base class in TypeScript

abstract class UnitOfWork {
  abstract commitChanges(): Promise<void>;
}

About this code snippet:

  • The method commitChanges is used asynchronously every time we want to perform the transaction.

Example of the implementation of the Unit of Work in TypeScript

For this example I am using MikroORM:

MikroORM

MikroORM is an ORM for JavaScript and TypeScript that allows handling transactions automatically, it has a function called flush(), which will make all the changes in the transaction be applied to the database.

import { MikroORM, UnitOfWork as MikroOrmUnitOfWork } from '@mikro-orm/core';
import { Injectable } from '@nestjs/common';
import { UnitOfWork } from '../../domain/repositories';

@Injectable()
export class UnitOfWorkMongoDb
  extends MikroOrmUnitOfWork
  implements UnitOfWork
{
  constructor(private readonly orm: MikroORM) {
    super(orm.em);
  }

  public commitChanges(): Promise<void> {
    return this.orm.em.flush();
  }
}

About this code snippet:

  • An alias is assigned on the import of UnitOfWork from @mikro-orm/core because its have the same name as our Unit of Work base class.
  • MikroORM is injected into the constructor using dependency injection.