Event Pattern Matching
Function-Based Matchers
// A pattern is a function that returns true or false for an event type
node.on(eventType => eventType === 'order.submitted', (event, context) => {
// Process order submission
// ...
// Return next function or result
return processPayment;
});// Match exact event type
node.on(type => type === 'order.submitted', handleOrderSubmission);
// Match events by domain prefix
node.on(type => type.startsWith('order.'), (event, context) => {
// Log all order events
logOrderEvent(event);
// Continue to domain-specific handler
return getDomainSpecificHandler(event.type);
});
// Match multiple specific events
node.on(type => ['payment.succeeded', 'payment.failed'].includes(type),
function(event, context) {
// Process payment result
processPaymentResult(event);
// Branch based on success or failure
return event.type === 'payment.succeeded' ?
handlePaymentSuccess : handlePaymentFailure;
}
);
// Match with regular expressions
node.on(type => /^user\.(created|updated|deleted)$/.test(type),
function(event, context) {
// Handle user lifecycle event
updateUserCache(event);
// Determine next step based on event type
const actions = {
'user.created': notifyUserCreated,
'user.updated': notifyUserUpdated,
'user.deleted': notifyUserDeleted
};
// Return appropriate next function
return actions[event.type];
}
);
// Complex conditional matching
node.on(type => {
const [domain, action] = type.split('.');
return domain === 'inventory' && action.includes('level');
}, function(event, context) {
// Process inventory level event
processInventoryLevel(event);
// Check if restock needed
if (isRestockNeeded(event.payload)) {
return createRestockOrder;
}
// Otherwise complete
return { processed: true };
});Creating Your Own Pattern System
String Pattern Support
Building Domain-Specific Pattern Systems
Benefits of Function-Based Pattern Matching
Best Practices
Last updated