TypeORM doesn't have repositories

It's true, TypeORM doesn't implement Repository pattern, despite it has something called a repository. Let's figure out why.

There is a Data Mapper pattern, which has one responsibility – to transfer data between a domain model and a database, in other words, create objects with data and save them back to database.

In the view of many developers, behaviour of a data mapper pattern is exactly what repositories do. But repositories have a different purpose – to imitate a collection.

We all know that objects are passed by reference. And, therefore, having received a reference to an object, you can mutate this object as you wish. But in the case of the data mapper, this ideal picture of the world collapses. Firstly, a data mapper returns a new object with each call, and secondly, it will not know about any manipulations with an object, and as a result, you will have to call dataMapper.save to write an object state to a database.

It looks like there is need for another layer on top of data mapper.

Here a repository comes into play, which, as I already said, imitates a collection of objects. If you correctly implement a repository, it is enough to write the following code to change state in the database:

The following would also be valid:

But how changes will get into the database? A data mapper still can't detect that object has been mutated. It seems that we still need the repository.save method...

No. This problem has a solution called Unit of Work – this is another pattern that is implemented on top of the previous two and determines boundaries of working with objects.

Code with Unit of Work, Repository and Data Mapper will look like:

As a result of the code above, UoW will count all changes that have occurred in repositories and call necessary methods on a date mapper, so there will be 2 records in the database: one with the old user whose name was updated, and a second with the new Гриша.