vendredi 30 août 2019

Node.js - Avoiding multiple calls to the database

I'm building a REST API using Node.js (express). The project structure is divided into three parts(which is said to be a common architecture for a REST API).

  • Database Layer (code related to database config & querying functions) e.g. `db.fetchUser()`
  • Services (code related to app logic) e.g. `authSerivce.authUser()` & `authService.genAuthToken()`
  • Controllers (code related to a specific route) - Service functions are used here.

authService.authUser() service function calls db.fetchUser(username) which returns
username and password from the database. Then it authenticates the user and returns the authentication result. After that I call authService.genAuthToken(username) to generate an
authentication token and send it to the user. So for user login, I will have to do:

const authResult = authService.authUser(username, password);
if(authResult.failed) return;
const token = authService.genAuthToken(username);

The authService.genAuthToken(username) will have to call db.fetchUser() again (to access name & user role) to generate the proper authentication token.
So I will have "two" database calls because of the project architecture.

How can this issue be solved?

I thought of passing the connection instance to the service functions along with other parameters but that seems wrong too.
The design gets more complex and scattered if I use transactions.

Thanks

Aucun commentaire:

Enregistrer un commentaire