Reputation: 590
In Node it's really easy to create an evented architecture. But what if I have a client of a streaming API (via socket.io) that I don't control, and my client needs to react differently based on varying sequences of events.
Example of 2 different sequences:
So far I am using Transform Streams and I'm thinking of creating complicated custom logic that buffers desired messages when I need to and acts upon them, but I wanted to know if there are best practices to deal with that kind of situation.
Thanks
Upvotes: 2
Views: 205
Reputation: 5385
The idea would be to define a set of objects which define your event sequences and when you get the first event that matches, you copy that sequence and then pop elements of the array until you have no more elements. If you encounter an event which doesn't match, you reset your current buffer.
var events = [
{ sequence : ['event 1', 'event 2', 'event4']
handler: firstSequenceHandler
},
{ sequence : ['event 3', 'event 2']
handler: secondSequenceHandler
}
];
Subscribe to your event stream:
var eventbuffer;
var handler;
on('data', function(event){
if(eventbuffer){ // we already have started a sequence:
var expectedEvent = eventbuffer.pop(); // get the next expected event
if(expectedEvent === event && eventbuffer.length===0)
return handler();
else{
// reset buffer:
eventbuffer = null;
handler = null;
}
}
// check if the event is in your list of events as the first item.
// if so
eventbuffer = event.sequence.slice(0); // copy the sequence.
handler = event.handler;
eventbuffer.pop(); // remove the first element as you found it.
));
Upvotes: 1