I’ve recently implemented this in a project and can share how I did it. Unsure if it is the best practices way as the docs didn’t really cover it. But it seems to work. It’s using the stream events to separate out regular events and error events.
class EventStoreDbSubscriber {
private subscription: AllStreamSubscription
constructor(
) {
void this.startSubscription()
}
async startSubscription() {
this.subscription = client.subscribeToAll()
this.registerSubscriptionHandlers()
}
registerSubscriptionHandlers() {
this.subscription
.on('data', (resolvedEvent: AllStreamResolvedEvent) => {
const event = resolvedEvent.event
// Handle the event
})
.on('error', (err) => {
// 'err' should have the subscription dropped reason
// Destroying this subscription will emit a 'close' event and we will try to reconnect
this.subscription.destroy()
})
.on('confirmation', () => {
console.log('EventStoreDb connection established')
})
.on('close', () => {
console.log('EventStoreDb connection closed. Attempting to reconnect in 5 seconds')
setTimeout(() => {
void this.startSubscription()
}, 5000)
})
}
}