I’ve recently developed a REST API utilizing a layered architecture comprising routes, controllers, models, and a data access layer (DAL) with repository and entity classes.
While this structure has served my project well so far, I’m curious about the expected conventions regarding the responsibilities within each layer and how they align with traditional patterns.
Specifically, I’d like to inquire about:
-
The standard responsibilities allocated to each layer in such a setup.
-
How the model layer should interact with the controller layer, considering the deviation from the conventional MVC architecture. Does it serve as some sort of Data Transfer Object on top of the DAL entity, or does it merely validate and wrap the DAL repository? For instance, if I have entities like Person, PersonToPosition, and Position, should I create a DTO to bundle them together? Additionally, where and on which layer should I combine these entities?
-
Are there any best practices or recommended approaches for maintaining separation of concerns and ensuring code maintainability in this architecture?
I would greatly appreciate any advice, examples, or references to authoritative resources.
Thank you in advance for your guidance.
-
Error handling while dealing with multiple layers helps simplify the code but also confuses me when it comes to error handling. For example, if a non-existent object is retrieved from the API (e.g., via HTTP GET on “person/1” where no person with such a key exists), where should I test for errors? Should it be at the route layer only, in the controller, or elsewhere?
-
In one of my projects, I had to create an “init_db” function for a MongoDB ORM. This function is responsible for initializing the ORM motor and must run before the application starts. This behavior doesn’t fit the DAL layer because the architecture advocates separation between the different layers, allowing them to communicate only with the layer above them. Therefore, I placed this behavior in a layer I named middleware. However, I find this solution somewhat lacking because now readability is affected by searching for something related to the data layer in a different layer.