Best Way to Inject Repositories using TypeORM (NestJS)
Published in
5 min readJul 14, 2020
Taking Class-Transformer & TypeORM in NestJS & comparing them with Laravel Collections & Query Builder, I am today going to explain how to minimize writing too much code & getting similar outputs. I have been using TypeORM as part of NestJS for a long time now & really believe that it holds almost the same capabilities as its competitor in Laravel / PHP.
Let me first explain the main reasons why custom repositories will keep you at a greater advantage.
- Too Much Code — IMO, the default TypeORM repos are helpful for smaller projects only. If you however have a project with over 10 different models having CRUD abilities in almost all of them, you’d end up writing too much code.
- Custom Functions Must Be Made Part of Services — The inability to create/run custom functions within the repositories will make you re-write CRUD functionalities within your services. And again, because of this, you’d end up re-writing a lot of code within different services.
- Non-Serialized Output — By default, any data retrieved by using TypeORM’s query builder is in the form of an entity which is not serialized since functionalities of
class-transformer
are not built within TypeORM. This therefore forces you to serialize all your outputs within your service, rather than your repository.