Last active
December 5, 2016 18:47
-
-
Save marcbachmann/8b0e774652a4c1820fba3175433bc3a9 to your computer and use it in GitHub Desktop.
In memory eventsourcing repository
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
var util = require('util') | |
var EventEmitter = require('events').EventEmitter | |
var _ = require('lodash') | |
var Aggregate = require('eventsourced-object') | |
function InMemoryRepository (Model) { | |
this.eventCount = 0 | |
this._Model = Model | |
} | |
util.inherits(InMemoryRepository, EventEmitter) | |
InMemoryRepository.prototype.get = function (item, cb) { | |
var agg = this.aggregates && this.aggregates[item.aggregateId] | |
if (_.isEmpty(agg) || agg[0].context !== item.context) cb(new Error('Not found')) | |
else cb(null, new this._Model(agg)) | |
} | |
InMemoryRepository.prototype.save = function (agg, cb) { | |
if (!this.aggregates) this.aggregates = {} | |
var events = Aggregate.drain(agg) | |
var first = events[0] | |
if (!first) return cb(null, null) | |
if (!this.aggregates[first.aggregateId]) this.aggregates[first.aggregateId] = [] | |
var a = this.aggregates[first.aggregateId] | |
var event | |
if (((a.length || 0) + 1) !== first.version) return cb(new Error('Conflict')) | |
for (var i = 0; i < events.length; i++) { | |
events[i].id = ++this.eventCount | |
a[a.length] = events[i] | |
} | |
cb(null, null) | |
// Events are triggered after saving the events | |
for (var i = 0; i < events.length; i++) this.emit('data', events[i]) | |
} | |
InMemoryRepository.prototype.events = function (params, cb) { | |
if (params.aggregateId) return cb(null, this.aggregates[params.aggregateId]) | |
var events = _.chain(this.aggregates).values().filter(Boolean).flatten().value() | |
if (params.context) cb(null, _.filter(events, {context: params.context})) | |
else cb(null, events) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment