-
Notifications
You must be signed in to change notification settings - Fork 9
/
snapshotter.coffee
51 lines (44 loc) · 1.92 KB
/
snapshotter.coffee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Space.eventSourcing.Snapshotter extends Space.Object
@snapshotsCollection: null
dependencies: {
configuration: 'configuration'
ejson: 'EJSON'
injector: 'Injector'
mongo: 'Mongo'
}
collection: null
versionFrequency: 0
onDependenciesReady: ->
if Snapshotter.snapshotsCollection?
SnapshotsCollection = Snapshotter.snapshotsCollection
else
collectionNameEnvVar = 'SPACE_ES_SNAPSHOTTING_COLLECTION_NAME'
collectionDefaultName = 'space_eventSourcing_snapshots'
snapshotsName = Space.getenv collectionNameEnvVar, collectionDefaultName
mongoConnection = @configuration.eventSourcing.mongo.connection
SnapshotsCollection = new @mongo.Collection snapshotsName, mongoConnection
Snapshotter.snapshotsCollection = SnapshotsCollection
@collection = SnapshotsCollection
@versionFrequency = @configuration.eventSourcing.snapshotting.frequency
@injector.map('Space.eventSourcing.Snapshots').to SnapshotsCollection
@injector.get('Space.eventSourcing.Repository').useSnapshotter this
makeSnapshotOf: (aggregate) ->
id = aggregate.getId().toString()
currentVersion = aggregate.getVersion()
# Return early before the first snapshot point is reached
if(currentVersion) < @versionFrequency then return
data = @collection.findOne _id: id
data?.snapshot = @ejson.parse(data.snapshot)
snapshot = aggregate.getSnapshot()
if data? and data.snapshot.version <= currentVersion - @versionFrequency
# Update existing snapshot of this aggregate
@collection.update {_id: id}, $set: snapshot: @ejson.stringify(snapshot)
else if !data?
# Insert first snapshot of this aggregate
@collection.insert _id: id, snapshot: @ejson.stringify(snapshot)
getSnapshotOf: (Type, id) ->
record = @collection.findOne(_id: id.toString())
if record?
return Type.createFromSnapshot @ejson.parse(record.snapshot)
else
return null