-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathitemAggregate.js
83 lines (67 loc) · 2.29 KB
/
itemAggregate.js
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// the itemAggregate is the aggregationRoot for a single item all commands concerning this
// aggregate are handled inside this object.
var colors = require('./colors');
// the itemAggregate has an internal state (id, text, destoyed)
var Item = function(id) {
this.id = id;
this.text = '';
this._destroy = false;
this.uncommittedEvents = [];
};
Item.prototype = {
// each __command__ is mapped to an aggregate function
// after validation the __event__ is applied to the object itself (changing
// the internal state of the aggregate)
//
// when all operations are done the callback will be called.
createItem: function(evt, callback) {
evt.payload.id = this.id;
if (evt.payload.text === '') {
callback(new Error('It is not allowed to set an item text to empty string.'));
} else {
this.apply(evt);
callback(null, this.uncommittedEvents);
}
},
changeItem: function(evt, callback) {
if (evt.payload.text === '') {
callback(new Error('It is not allowed to set an item text to empty string.'));
} else {
this.apply(evt);
callback(null, this.uncommittedEvents);
}
},
deleteItem: function(evt, callback) {
this.apply(evt);
callback(null, this.uncommittedEvents);
},
// apply the event to the aggregate calling the matching function
apply: function(evt) {
this['_' + evt.event](evt);
if (!evt.fromHistory) {
this.uncommittedEvents.push(evt);
}
},
_itemCreated: function(evt) {
this.text = evt.payload.text;
},
_itemChanged: function(evt) {
this.text = evt.payload.text;
},
_itemDeleted: function(evt) {
this._destroy = true;
},
// function to reload an itemAggregate from it's past events by
// applying each event again
loadFromHistory: function(history) {
for (var i = 0, len = history.length; i < len; i++) {
e = history[i].payload;
e.fromHistory = true;
this.apply(e);
}
}
};
// export the modules function to create a new itemAggregate
exports.create = function(id) {
return new Item(id);
};