I'm just starting learning node.js, express and mongoose. In some tutorial I see some project structure like they have different folder for controller, different for services , different for data access layer.
Now my question is what is the difference in services and data access layer file, what we keep there? And where we keep data access layer file in my project structure?
Also what exactly the task of controller and routes ?
The routes files are where you place the application endpoints. Those will refer to the specific application methods you define. This is called routing.
app.post('/users', userController);
For clarification, in the example above we're calling the POST HTTP method for the /users route and redirecting the request to the userController method.
The controller layer is more specific. He is responsible for parsing the HTTP request data and sending it to the service layer.
For example:
async function userController(request, response) {
const { name, age } = request.body;
const serviceRequestBody = { name, age };
const serviceResponse = await userService(serviceRequestBody);
return response.json(serviceResponse);
}
The service layer is normally where you place the project rules (domain specific rules). For example: calculating the birth year based on the user age.
async function createUserService(userData) {
const birthYear = new Date().getFullYear() - userData.age;
const userFormatedData = {...userData, birthYear }; // the three dots means that we're getting all the information inside userData and placing it inside the new variable.
const dbResult = await userRepository(userFormatedData);
return dbResult;
}
The data access layer (can also be called "repository") is responsible for getting, posting, updating or deleting the information from the database.
async function userRepository(userInfo) {
const dbResult = await db.post(userInfo);
return dbResult;
}
For the project structure, its more up to you. I like to structure my projects like this:
-src
|-modules
| | -user // domain specific entities. If you have other entities, they will be inside another folder with the same structure as this one
| |-domain
| |-controllers
| |-repositories
| |-routes
| |-services
|-shared // can be used across any module
|-utils
|-providers
-package.json
-configFile.json
PS: Those abstractions may vary over time as you scale your application. It's the engineer's responsibility to figure out a better structure according to the case he's facing.
If you want to learn more about software engineering, search for Domain Driven Design (DDD), which is set of architecture rules that composes a good and scalable project.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With