#How do you usually organize your entities, dto's, types (not .d.ts) and modules?

8 messages · Page 1 of 1 (latest)

simple viper
#

I'm new with Nest, coming from ASP.NET. I'd like to know what best practices you have in Nest for the project architecture.

tight turtle
#

I usually keep my database layer in its own lib and follow the repository pattern. That way I don’t have to pull in random services just to use entities, and if I ever move to a monorepo setup it’s already clean.

My structure looks something like this:

libs/
  database/
    src/
      common/               -> base entities, base repo, unit of work
      config/               -> default + migration config
      entities/             -> all DB entities
      migrations/           -> migration files
      repository-manager/   -> central module that manages repos/queries
      seed/                 -> seeding logic
      types/                -> db-related types
    database.module.ts

This setup keeps everything DB-related in one place, while services just depend on repositories instead of each other. Keeps things modular and easy to swap out later if needed.

chrome tundra
ripe carbon
#

the short story is to build your file structure as "features"
as for a example "authentication" would have its own dedicated folder in the src

a database for example in particular is more of a "dependency" rather then a feature
its better to keep those together in a folder like src/common/database
you still want this "dependency" to have its own folder but not clutter the src with this

a guard, middleware pipe, etc not bound to a particular "feature" isn't a "dependency" either
what about a folder like src/global makes sense right?
if i would need to give a example and lets use a guard for this i think src/global/guards makes sense for this

the nest cli is actually great at filling in the files needed for a "feature" using nest g res <feature name>
if you where wondering how the structure of a "feature" should look like

each feature guard or dependency you make should still have its own named folder
but this is something the cli will handle too as long as you generate it at the right place

elder robin
chrome tundra
tight turtle
chrome tundra
#

Yes, define the entities in the module that needs them (this is why you see forFeature methods everywhere) and if you have a database access layer, make that a core module, but only defining the forRoot or forRootAsync as part of the core db module. Then, make the core module a dependency of your user module. So, both the core and the user module would be libraries you could import into any other application. Code reuse for the win! 😄