Created
June 7, 2017 15:09
-
-
Save johncoder/acf39cbf7699ca7667cedc05c658a392 to your computer and use it in GitHub Desktop.
event store sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Buffer = require('buffer').Buffer; | |
const uuid = require('uuid/v4'); | |
const eventstore = require('eventstore-node'); | |
const eventstoreUrl = process.env.EVENTSTORE_URL || 'tcp://localhost:1113'; | |
const connSettings = {}; | |
const esConnection = eventstore.createConnection(connSettings, eventstoreUrl); | |
esConnection.connect(); | |
esConnection.once('connected', endpoint => { | |
console.log(`Connected to eventstore at ${endpoint.host}:${endpoint.port}`); | |
}); | |
function stream(streamName) { | |
return async function sendMessage(message, type) { | |
const id = uuid(); | |
const event = eventstore.createJsonEventData(id, message, null, type); | |
process.stdout.write('.'); | |
try { | |
const result = await esConnection.appendToStream(streamName, eventstore.expectedVersion.any, event); | |
process.stdout.write(':'); | |
} catch (exception) { | |
console.error(`Error sending ${id}: ${exception}`); | |
} | |
}; | |
} | |
const send = stream('hello-world'); | |
const writing = process.env.WRITING === 'true'; | |
if (writing) { | |
setInterval(() => { | |
send({ | |
message: 'hello world!', | |
value: uuid(), | |
created: (new Date()).toISOString(), | |
}, 'pulse'); | |
}, 10); | |
} else { | |
setImmediate(async function resume() { | |
try { | |
const start = new Date(); | |
const result = await esConnection | |
.readStreamEventsForward('hello-world', 0, 4096); | |
const events = result.events.map(e => ({ | |
id: e.event.eventId, | |
number: e.event.eventNumber, | |
type: e.event.eventType, | |
created: e.created, | |
event: JSON.parse(Buffer.from(e.event.data).toString('utf8')), | |
})); | |
let c = 0; | |
events.forEach(() => c++); | |
const finish = new Date(); | |
console.log(`done loading ${c} events in ${finish - start}ms`); | |
} catch (exception) { | |
console.error(`Error resuming: ${exception}`); | |
} | |
}); | |
} | |
console.log('started...'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment