Redux on Server?
September 26, 2021
Recently I was adding functionality to humongous function. The function was huge because of its complex functionality. But the function itself was doing little computation and was just calling other functions to do the computation.
function humongousFunction() {
logic1()
logic2()
.
.
.
logicN()
}
But few of the internal functions were fetching data same data from the database. But these functions were also being called from other places.
function logic1() {
fetchXFromDB()
fetchYFromDB()
}
function logic2() {
fetchXFromDB()
fetchZFromDB()
}
So, we have two options:
- Pass the variables in the params
- Fetch the data from the Database in the function itself (which is what was happening in my case)
Both options have their arguments. The first option is more optimized for performance, whereas the second option decouples our functions.
But I think there’s a better solution to achieve both of these advantages. The solution borrows its idea from Redux. The idea is to implement a redux like storage on the server:
- The storage gets instantiated for each request.
- On a database query, data gets added to this storage, with the query as its key.
- Next time, when another function in the same request tries to fetch the same data, the data is returned from the storage.
- Once the request is processed, the storage instance will be destroyed.
This will be optimized, and will also allow us to write functions without having to worry about coupling.
Hello 👋
Subscribe for wholesome stuff about life, tech, football, physics and everything else.
No spam, and there's unsubscribe link in every message.