forked from jchadwick/EssentialTypeScript
-
Notifications
You must be signed in to change notification settings - Fork 1
/
TodoService.ts
133 lines (92 loc) · 2.79 KB
/
TodoService.ts
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
import { Todo, TodoState } from './Model';
import { ValidatableTodo } from './Validators';
export interface ITodoService {
add(todo: Todo): Todo;
add(todo: string): Todo;
clearCompleted(): void;
getAll(): Todo[];
getById(todoId: number): Todo;
toggle(todoId: number): void;
}
let _lastId = 0;
function generateTodoId(): number {
return _lastId += 1;
}
function clone<T>(src: T): T {
var clone = JSON.stringify(src);
return JSON.parse(clone);
};
export default class TodoService implements ITodoService {
private todos: Todo[] = [];
constructor(todos: string[]) {
if (todos) {
todos.forEach(todo => this.add(todo));
}
}
// Accepts a todo name or todo object
add(todo: Todo): Todo
add(todo: string): Todo
@log
add(input): Todo {
var todo = new ValidatableTodo();
todo.id = generateTodoId();
todo.state = TodoState.Active;
if (typeof input === 'string') {
todo.name = input;
}
else if (typeof input.name === 'string') {
todo.name = input.name;
} else {
throw 'Invalid Todo name!';
}
let errors = todo.validate();
if(errors.length) {
let combinedErrors = errors.map(x => `${x.property}: ${x.message}`);
throw `Invalid Todo: ${combinedErrors}`;
}
this.todos.push(todo);
return todo;
};
clearCompleted(): void {
this.todos = this.todos.filter(
x => x.state == TodoState.Active
);
}
getAll(): Todo[] {
return clone(this.todos);
};
getById(todoId: number): Todo {
var todo = this._find(todoId);
return clone(todo);
};
toggle(todoId: number): void {
var todo = this._find(todoId);
if (!todo) return;
switch (todo.state) {
case TodoState.Active:
todo.state = TodoState.Complete;
break;
case TodoState.Complete:
todo.state = TodoState.Active;
break;
}
}
private _find(todoId: number): Todo {
var filtered = this.todos.filter(
x => x.id == todoId
);
if (filtered.length) {
return filtered[0];
}
return null;
}
}
function log(target: Object, methodName: string, descriptor: TypedPropertyDescriptor<Function>) {
let originalMethod = descriptor.value;
descriptor.value = function(...args) {
console.log(`${methodName}(${JSON.stringify(args)})`)
let returnValue = originalMethod.apply(this, args);
console.log(`${methodName}(${JSON.stringify(args)}) => ${JSON.stringify(returnValue)}`)
return returnValue;
}
}