Closed StevenBlair123 closed 3 months 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);
}
});
Might be a nice blog post if there was any interest.
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
Add a handler in for the initShared:
Now, in my projection I can access my partition and shared state like this:
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