The event driven face of Javascript
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?
The Example
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.
The Lesson
What does the above example have to do with event emitters? This example taught me a valuable lesson about javascript and Event Emitters. A lot of objects in javascript are event emitters. An Express request is an event emitter so is an Express response. If you look at HTML elements ( in the context of js ofc ), every single one is an event emitter. Even the file system module in NodeJS is an event emitter. These being event emitters means you can write event-driven and loosely coupled code. And that helps you create maintainable features with fewer lines of code.
Conclusion
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.