Event Store Projections – Distributing events to other streams

Since the GameOver events are appended to the Game stream, we need a way to distribute them to all participating players’ streams. The GameOver event contains a list of participating players, and the distributor emits an event for each player. The event type emitted depends on how much the player has won or lost: if the amount is less than zero, a GameLost event is emitted, but if the amount is greater than zero, a GameWon event is emitted instead. (For simplicity’s sake, we’ll assume GameDraw events don’t exist.)

Note that we don’t technically have to split the event in two to implement our alarm system, but it’s useful for the purposes of this example.

Projection GameOverToPlayerDistributor

This projection takes GameOver events from all Game streams as input. For each GameOver event, it will loop over the list of players and distribute (i.e. emit) GameLost and GameWon events to the players’ streams as appropriate.

Projection-GameOverToPlayerDistributor-Events

JavaScript implementation

This projection module has a single public method, process, which processes the GameOver events by looping over the participating players and emitting the appropriate events:

This module is instantiated once globally and then referenced from the projection’s definition:

Testing the projection

To test this projection, we’ll define three scenarios. The first will arrange an event with a positive amount and assert that a GameWon event is emitted. The second will arrange an event with a negative amount and assert that a GameLost event is emitted. The last will check for a combination of both.

Querying the results with the Client API

The results of this projection are used solely as input for another stream, so there’s no need to read them with the C# Client API.

Source code

A working project for this example can be found on github: https://github.com/tim-cools/EventStore-Examples

Event Store Projections by Example

This post is part of a series:

  1. EventStore Client API Basics (C#)
  2. Counting events of a specific type
  3. Partition events based on data found in previous events
  4. Calculating an average per day
  5. The irresponsible gambler
  6. Distribute events to other streams
  7. Temporal Projection to generate alarms
  8. Projection in C#

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *