I am completely new to ES, so apologise in advance for the stupid question. I’m trying to use projections in JS to process different event types from a single stream to build up state per policy_id and write to a new stream when a certain event is encountered (insurance_policy.bound).
The source stream has the following event types per policy_id:
- insurance_policy.created
- Many insurance_policy.rate_added
- insurance_policy.bound
My code is below and I am wondering about the following:
- How does the projection know to partition the state per policy_id
- I am wondering do I need to do “Reset state after flushing to new stream” part? If I remove
s.rates = []
I get rates being mixed up in the emitted event from different policy rate_added events.
fromStream('policies')
.when({
$init:function(){
return {
transaction_type: null,
policy_id: null,
agency_data: {},
rates: []
}
},
"insurance_policy.created": function(s, ev){
s.policy_id = ev.data.insurance_policy_id
},
"insurance_policy.rate_added": function(s, ev) {
s.rates.push({
policy_rate_id : ev.data.insurance_policy_rate_id,
key : ev.data.key
})
},
"insurance_policy.bound": function(s, ev) {
s.transaction_type = 'bound'
emit(
'analytics.policy_transactions',
'policy_bound',
s
)
// Reset state after flushing to new stream
s.transaction_type = null
s.policy_id = null
s.agency_data = {}
s.rates = []
}
})
Thank you for your help.
Jag