Are there any good patterns for controlling flow based on sequences of events in Node?

StackOverflow https://stackoverflow.com/questions/17700488

  •  03-06-2022
  •  | 
  •  

Domanda

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:

  • first order placed > 2nd order placed
  • first order placed > first order hit by a trade > 2nd order placed

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

È stato utile?

Soluzione

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.
));
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top