Node.js: The case of event handling patterns
Node.js: The case of event handling patterns
Events in node.js have become a day to day used programming construct. Along with it comes the need for adopting event emitters in various programming patterns.
**Note** With available time I have given code samples only for the first pattern. Samples for rest of the patterns to follow in updates.
Chain of responsibility
Usually there are multiple observers listening to an event and node.js will notify all of them at the same time. But sometimes the requirement might necessitate executing the observers in an order, instead of notifying all at the same time. This means we need to notify each observer asynchronously and wait for its response before executing the next.
With node version 10 we have the async iterators and the for-await key word to get this done. In the below example, we have a publisher which emits various events. It has a map to correlate every registered event with an async iterator and a list of observers.
While the async-iterators are a pretty interesting topic by themselves here we simplify it by using an available iterator module, p-event
. The for-await in the above code block has now become a background listener and will loop over when ever a new event is added to the iterator.
Next, let’s add multiple observers for the events.
The subscriber above adds 10 observers for two events event1 and event2. We expect now the event notifier to execute the observers in the order of addition.
Lets check what is the output when we execute the above code snippet.
We see that the event observers are executed in an order, though they have different execution times.
Event aggregation
Many events might need a single observer and so grouping of events is necessary. There is already some explanation on this from martin fowler.
An Event Aggregator is a simple element of indirection. In its simplest form you have it register with all the source…martinfowler.com
Fan-Out Fan-In
Similar to grouping of events into a single event there is also a need for splitting events and later merging them to an end event. This is an ideal case for creating small parallel actions for a process with a huge memory foot print.
Event Sequencing
Certain use cases need ordering of events by some sequence and linking of them similar to a linked list. Subscribers are often puzzled on how to process out of order events in webhook apis like shopify, chargebee, etc.
Replaying a Recipe
In this pattern, we have a “preparer” who creates or updates a composite object with smaller parts. The “preparer” notes the changes made in an “action-queue”. No other updates are allowed on the constituent parts until the composite object is in “ready” state. When the composite object is in “ready” state then the actions are replayed from the “action-queue” to the observers in the same order.