1
votes

Recently I started working on the backend (for my personal project) and I chose nestjs and for ORM I chose typeorm.

Now I want custom repositories so that I can have an abstract base repository that implements all needed methods and then inherit those in the actual entity repository. So, how can I structure my project? should I create a module that exports all repositories, or is there any other efficient way?

1

1 Answers

0
votes

I've just recently began using NestJS but this is how I've been structuring my project and has worked fairly well so far. Each endpoint has it own module and each module contains all thing related to that endpoint. An example might be an accounts endpoint. I'd have an accounts module which would contain all things related to an account (entities, service, controllers, dtos, etc).

For any shared items that will be used across multiple modules I've created a common module. Inside the common module I'd keep all shared interfaces, base entities, base repositories, and shared services.

So my file structure would look something like this...

|-- accounts
|   |-- controllers
|   |   |-- accounts.controller.ts
|   |   |-- profiles.controller.ts
|   |-- entities
|   |   |-- account.entity.ts
|   |   |-- profile.entity.ts
|   |-- repositories
|   |   |-- accounts.repository.ts
|   |   |-- profiles.repository.ts
|   |-- services
|   |   |-- accounts.service.ts
|   |   |-- profiles.service.ts
|   `-- accounts.module.ts
|-- common
|   |-- entities
|   |   |-- base.entity.ts
|   |-- repositories
|   |   |-- base.repository.ts
|   |   |-- repository.interface.ts
|   |-- services
|   |   |-- some-shared-service.service.ts
|   |   |-- another-shared-service.service.ts
|   `-- common.module.ts
|-- products
|   |-- controllers
|   |   |-- products.controller.ts
|   |-- entities
|   |   |-- product.entity.ts
|   |-- repositories
|   |   |-- products.repository.ts
|   |-- services
|   |   |-- products.service.ts
|   `-- users.module.ts

The sub-directories (entities, repositories, service, etc) inside the modules might be overkill and unnecessary so you could flatten the structure but the idea was to keep the common files shared across multiple modules in their own module called common. Each module that needs the common file/services could import the common module.