This repository has been archived by the owner on Nov 10, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtodolist.js
100 lines (86 loc) · 2.39 KB
/
todolist.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
var {AggregateRoot} = require("@serialized/serialized-client")
class TodoListCreated {
constructor(todoListId, name) {
this.eventType = 'TodoListCreated';
this.data = {
todoListId,
name
}
}
}
class TodoListCompleted {
constructor(todoListId) {
this.eventType = 'TodoListCompleted';
this.data = {
todoListId,
}
}
}
class TodoAdded {
constructor(todoListId, todoId, text) {
this.eventType = 'TodoAdded';
this.data = {
todoListId, todoId, text,
};
}
}
class TodoCompleted {
constructor(todoListId, todoId, text) {
this.eventType = 'TodoCompleted';
this.data = {
todoListId: todoListId,
todoId: todoId,
text: text,
};
}
}
class TodoList extends AggregateRoot {
constructor(todoListId) {
super(todoListId, 'list')
if (!todoListId || todoListId.length !== 36) throw "Invalid listId";
this.todoListId = todoListId;
this.todos = [];
this.todosLeft = [];
this.completed = false
}
createList(name) {
if (!name || name.length < 5) throw "Name must have length >= 5";
this.saveEvents([new TodoListCreated(this.todoListId, name)])
}
addTodo(todoId, text) {
if (this.completed) throw "List cannot be changed since it has been completed";
if (text === undefined || text.length < 5) throw "Text must have length > 4";
var todo = {todoId: todoId, text: text};
this.saveEvents([new TodoAdded(this.aggregateId, todoId, text)]);
}
completeTodo(todoId) {
if (this.todosLeft.indexOf(todoId) > -1) {
var events = [new TodoCompleted(this.aggregateId, todoId)];
if (this.todosLeft.length === 1) {
events.push(new TodoListCompleted(this.todoListId))
}
this.saveEvents(events);
} else {
// Don't emit event if already completed
return []
}
}
handleTodoListCreated(event) {
this.todoListId = event.data.todoListId;
this.name = event.data.name
}
handleTodoAdded(event) {
this.todos.unshift({text: event.data.text, todoId: event.data.todoId});
this.todosLeft.unshift(event.data.todoId)
}
handleTodoListCompleted(event) {
this.completed = true
}
handleTodoCompleted(event) {
// Remove from list
this.todosLeft = this.todosLeft.filter(function (todoId) {
return todoId !== event.data.todoId;
})
}
}
module.exports = {TodoList, TodoAdded, TodoListCreated, TodoCompleted, TodoListCompleted};