Managing Context in Express Application
Pre-requisite
- NodeJs
Why?
When creating a Web API, there is a need to manage a client’s context so that when it’s required in a function, the function gets the correct context and processes the data.
To achieve that, we often pass parameters to each function.
1 | //illustration |
Of course, it’s a very simple example.
Notice that getProducts(user)
doesn’t need a user but since updateUserLastVisit(user)
requires user data the function needed it.
What if we can store the user context and just get it when we need it down the function call?
enter continuation local storage. In simple terms, it allows us to store data for each request and delete it automatically when the chain call is finished.
Let’s start by creating a blank NodeJs project
1 | yarn init -y |
1 | # add express and continuation local storage dependencies |
Create src/index.js
.
1 | import Express from "express"; |
Try running it with
1 | node src/index.js |
There are going to be tradeoffs, one of which is testing, now you need to mock/stub the namespace call if you are running a unit test.
Conclusion
When you are building a complex application, you need to make a trade-off on how to manage your code, if you pass every variable that’s needed down in the function call even though your function might not need it your code will be harder to read, on the other hand, if you use context-based session like the one we did above, you will need extra effort on the test.