mardi 9 avril 2019

How to implement separation of concerns in Node.JS?

I have been trying to learn NodeJS for quite some time now. All the books and tutorials seems to follow similar pattern of structuring their code. Example -

const express = require('express');

const app = express();
app.set('view engine','hbs');

app.get('/', (req, res) =>{
    res.render('index');
});

app.get('/getName', (req, res) =>{
    // Mock DB call to fetch Name
    res.render('displayName');
});


app.listen(3000, () => {
    console.log("Started server on port : 3000");
});

As you can see above, the /getName controller is performing DB call as well as returning the view. So the business logic as well as the CRUD operation is being done at the same place.

I come from the world of JAVA and there we do it slightly differently. For example, a Spring Boot application would contain the following structure -

  • DTO
  • Repository
  • Service
  • Controller

So, controller classes are the actual endpoints which do not perform any business logic but call the underlying service class to handle all that. The service classes implement the business logic and persist/fetch data required for it with the help of the repository classes. The repository on the other hand handles the CRUD operations.

This seemed like a sane way to develop software. Given that each class has their defined roles, it becomes really easy to handle any change.

I understand the NodeJs is a dynamic but -

1. Is there a way to separate out the functionality like we do in Spring ? If not,

2. How to structure large projects having multiple endpoints and DB transactions.

Regards

Aucun commentaire:

Enregistrer un commentaire