Event Store Rest API Basics (Node.js)
Event Store Node.js client
I recently finished my first project written in Node.js with EventStore as data-store. I published the some of the code used to access the EventStore to github, feel free to play with it. The official documentation can be found the the EventStore web-site.
The code to load/save the events is coded in a repository and contains 3 methods:
1 2 3 4 5 | var repository = require("../libs/eventRepository"); repository.load(streamId, callback); repository.loadLast(streamId, callback); repository.save(streamId, version, events callback); |
Have a look at the implementation on github. And at jasmine test file for the full examples.
Loading the events of an aggregate
The load method loads all events of a stream to be able to replay them on an aggregate. The events are loaded in batch. (In this example per 5)
1 2 3 | GET http://localhost:2113/streams/streamId/head/backward/5?embed=body GET http://localhost:2113/streams/streamId/6/backward/5?embed=body GET http://localhost:2113/streams/streamId/1/backward/5?embed=body |
The load method returns the current version of the stream and all stored events:
1 2 3 4 5 6 7 8 | { version: 2, events: [ { name: 'event1', body: { a: 1, b: '3' } }, { name: 'event2', body: { a: 2, b: '2' } }, { name: 'event3', body: { a: 3, b: '1' } } ] } |
When the stream doesn’t exists, the load methods returns an empty event array with -1 as version. -1 should be used as version to save events to a new streams.
1 2 3 4 | { version: -1, events: [ ] } |
Load the last event of a stream
To get the state of an projection the last event of a stream is loaded. This is done by requesting the head of the stream.
1 | GET http://localhost:2113/streams/streamId/head |
The loadLast method returns the version of the stream, and the name and the body of the last event.
1 2 3 4 | { version: 2, evens: { name: 'event3', body: { a: 3, b: '1' } } } |
Saving the events of an aggregate
The save methods appends to specified event to the stream. It also performs a concurrency check based on the version. When the version is not correct the callback returns with an error.
1 2 3 4 5 6 | POST http://localhost:2113/streams/streamId Content-Type: application/json ES-ExpectedVersion: %version% [ ... events ] |
What’s next
In the next posts I describe how I managed projections and applied event-sourcing on an aggregate in JavaScript.
Source code
A working project for these examples can be found on github: https://github.com/tim-cools/EventStore-Node-Examples
Event Store Projections by Example
This post is part of a series: