Created
June 17, 2016 09:40
-
-
Save freddi301/97ab24d3a83e348028bc7ed204395fb7 to your computer and use it in GitHub Desktop.
Mongo EventStore with capped collection + throng
This file contains hidden or 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 mongodb = require('mongodb') | |
const Bluebird = require('bluebird') | |
class EventStore { | |
constructor(dbUrl, collectionName){ | |
this.db = mongodb.MongoClient.connect(dbUrl); | |
this.cappedCollection = this.db.then(db=> | |
db.createCollection(collectionName, { capped: true, size: 1024*1024 }) | |
.then(()=> db.collection(collectionName).createIndex({__t: 1}, {unique: true})) | |
.then(()=> db.collection(collectionName)) | |
) | |
this.spy(); | |
} | |
latest() { return this.cappedCollection.then(collection=>collection | |
.find().sort({ $natural: -1 }) | |
) } | |
insert(data) { return this.cappedCollection.then(collection=>collection | |
.insert(Object.assign({}, data, {__t: mongodb.Long("0")})) | |
) } | |
last__t() { return this.cappedCollection.then(collection=>collection | |
.find({__t: {$gt: mongodb.Long("0")}}, {__t: 1}) | |
.sort({ __t: -1 }).limit(1).toArray() | |
.then(docs=>docs.length ? docs[0].__t: 0) | |
) } | |
spy() { return this.cappedCollection.then(collection=>collection | |
.find({},{ tailable: true, awaitdata: true, numberOfRetries: -1 }) | |
.stream().on('data', console.log.bind(console)) | |
) } | |
} | |
module.exports = new EventStore('mongodb://localhost/test', 'EventStore') | |
const throng = require('throng') | |
throng(n=>{ | |
let x = 0; | |
while (x++<10) module.exports.insert({worker: n}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment