DEV Community

Discussion on: How to structure your Express and Node.Js project

Collapse
 
amrelmohamady profile image
Amr Elmohamady • Edited

It's preferable to put your business logic in a service layer that can access the DAL (data access layer) for loose coupling reasons like:

  • What if you have a Rest API and want to make an MVC version or vice versa use service layer so you don't repeat your logic

  • What if you need to change a third party service like moving from Google cloud storage to AWS S3, use service layer so you don't have to update every function using this service, you will only need to update one file (this service file)

I would use a validation layer before the controller which validates the request body, can be done with something like JOI, express-validator, express-validation, etc..

I would also import & export related layer file from a single entry point like:

controllers/

user.controller.js

index.js
Enter fullscreen mode Exit fullscreen mode

services/

storage.service.js

user.service.js

index.js
Enter fullscreen mode Exit fullscreen mode

and so on for other folders.

So, in index.js, you import other services/controllers and export an object with all services/controllers.

Finally, I suggest reading about dependency injection and its advantages.

Collapse
 
nermineslimane profile image
nermineslimane • Edited

I use this method for the routes, i create one single entry point for all my routes like follows
/routes
-exemple1.routes.js
-exemple2.routes.js
-index.routes.js
-exemple3.routes.js
and in my index.routes.js I export all the routes