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 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.
Categories
Automation scripting Development tools Front end web development Infrastructure Kubernetes Programming guide Security Software architectureTags
Recent Posts
Restart Kubernetes pods following a schedule using Helm
Restart Kubernetes pods following a schedule using Kubectl
Create an Azure Key Vault with RBAC role assignments using Terraform
Get the download url of the latest GitHub release using Bash
Get the download url of the latest GitHub release using PowerShell