Mongo EventStore with capped collection + throng
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})
})