EventStore / documentation

Next-gen documentation website
https://developers.eventstore.com/
10 stars 17 forks source link

Add a section for biState #346

Closed StevenBlair123 closed 3 months ago

StevenBlair123 commented 3 years ago

I was having a look through the Eventstore source code today and noticed the initShare (it's been bugging for ages how to make this work):

https://github.com/EventStore/EventStore/issues/1735

Anyway, it seems it was as simple adding this option on a projection

options({
    biState: true
})

Add a handler in for the initShared:

 $initShared: function(s,e){
          return { count: 0};  
  }

Now, in my projection I can access my partition and shared state like this:

$any: function(s,e){
    s[0].count++; //this is my partition state
    s[1].count++; //this is my shared state
}

Any chance this could get added to this section of the documentation?

https://developers.eventstore.com/server/v21.2/docs/projections/user-defined-projections.html#user-defined-projections-api

StevenBlair123 commented 3 years ago

Here is an example where we have been using the shared state:

const shared_state = 1;
const partition_state = 0;

options({
    biState: true
})
fromStreams('$et-ProductCreated', '$et-CustomerCreated')
    .partitionBy(function(e) {
        if (e.data.productId) {
            return "product-" + e.data.productId.replace(/-/gi, "");
        }
        return "shared"; //Need a partition for our shared state
    })
    .when({
        $init: function(s, e) {
            return {
                count: 0
            };
        },
        $initShared: function(s, e) {
            return {
                customers: {}
            }
        },
        $any: function(s, e) {
            if (e.eventType === "CustomerCreated") {
                if (s[shared_state].customers[e.data.customerId] === undefined)
                    s[shared_state].customers[e.data.customerId] = {
                        customerName: e.data.customerName
                    }
                return;
            }

            s[partition_state].count++;

            //Enrich the event
            e.data["customerName"]= s[shared_state].customers[e.data.customerId].customerName;

            emit("EnrichedProducts","ProductCreatedEnrichedEvent",e,null);
        }
    });
StevenBlair123 commented 3 years ago

Might be a nice blog post if there was any interest.