It’s not news that the number of assets is inversely proportional to maintainability. Lines and files of code are not an exception here. But how do you implement a feature that collects different data from all existing files?
I encountered a specific problem statement while working on a project. The project uses ExpressJS with some extra code for abstraction and error handling. So the request-response flow looked like this.
The context is that I have to send data to an external service using the middleware. The problem statement was that I had to send the data present in not just the request body but also from the response body. But how do I get data that will be available only after the middleware executes?
There were multiple ways to solve this, and I took the event-driven route. I added an event listener for an event with the name ‘response’ on the express response object in the middleware. The handler of this event did validations and sent the data to the external service. And then, in the formatApiResponse(), I emitted a ‘response’ event with the response body using the express response object. The event teleported the data back to the middleware, and the middleware took care of the rest.
I only had to make changes in two files, the middleware logic file, and the formatApiResponse logic file. And the result is a maintainable feature where I have to deal with only two files for modifying it.
Event-Driven Architecture is not something new. I used to think it was complex to understand and hard to implement. But it was just triggering events and doing something when an event occurs. Like every architecture out there, event-driven architecture is not a silver bullet. It is just a tool in the tool belt. And the ability to pick the right tool makes you an efficient engineer.