Unit of Work + Repository Pattern using TypeScript (NestJs) and TypeOrm

Recently, I have been doing a lot study about design patterns and how they can applied to everyday software creation to achieve good software design.

What are design patterns?

In software engineering, a design pattern is a general repeatable solution to a commonly occurring problem in software design. A design pattern isn't a finished design that can be transformed directly into code. - Source Making

There are different types of design patterns but for the scope of this article I would only be showing you how I implemented the Unit of Work pattern in TypeScript.

Unit of Work Pattern

The Unit of Work pattern is used to group one or more operations (usually database operations) into a single transaction or “unit of work”, so that all operations either pass or fail as one.

According to Martin Fowler, the unit of work pattern maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems.

If you are building an enterprise application using a layered architecture, you would probably have to apply the UoW pattern to structure your database operations. I personally consider managing database transactions in your service layer as a code smell.

The following steps demonstrates the idea of UoW pattern, it's not necessarily a working example.

Step 1: Unit of Work Interface and Class

First, we would create define an interface for our UnitOfWork and also implement the interface as shown below:

Step 2: Unit of Work Factory

Next, we would define a UoW factory. Here we use the factory method pattern to create an instance of the UoW. The method `makeUnitOfWork()` returns an instance of UoW based on the provide ormType.

Step 3: Make a Unit of Work

Now let's make a unit of work. In the following example, we would create a team and team members using TeamRepository and TeamMemberRepository (I assume you already have the two repositories). The reason why we are using UoW here is so that we make the entire steps of creating a team and the two team members an atomic operation such that if the creation of the team fails, the team members would not be created.

Hope this helps.

References:

  1. https://sourcemaking.com/design_patterns
  2. http://jasonwatmore.com/post/2015/01/28/unit-of-work-repository-pattern-in-mvc5-and-web-api-2-with-fluent-nhibernate-and-ninject
  3. https://martinfowler.com/eaaCatalog/unitOfWork.html
Show Comments