import { observable , action , computed } from 'mobx' ; import { TodoItem } from '../model/TodoItem' ; import { todosApi } from '../apiclient' ; export class TodoStore { @ observable todos : TodoItem [ ] = [ ] ; @ observable isLoading : boolean = false ; @ computed get activeTodoCount ( ) : number { return this . todos . reduce ( ( sum , todo ) => sum + ( todo . completed ? 0 : 1 ) , 0 ) ; } @ computed get completedCount ( ) : number { return this . todos . length - this . activeTodoCount ; } @ action loadTodos ( ) { this . todos = [ ] ; return todosApi . getAll ( ) . then ( action ( ( data ) => { data . forEach ( todo => this . todos . push ( new TodoItem ( todo ) ) ) ; } ) ) ; } @ action addTodo ( todo ) { const newTodo = { completed : false , title : todo } ; return todosApi . add ( newTodo ) . then ( action ( ( data ) => { this . todos . push ( new TodoItem ( data ) ) ; } ) ) ; } @ action editTodo ( id , title ) { return todosApi . patch ( id , { title : title } ) . then ( action ( ( ) => { let todo = this . todos . find ( t => t . id === id ) ; todo . title = title ; } ) ) ; } @ action deleteTodo ( id ) { return todosApi . remove ( id ) . then ( action ( ( ) => { let todo = this . todos . find ( t => t . id === id ) ; const index = this . todos . indexOf ( todo ) ; this . todos . splice ( index , 1 ) ; } ) ) ; } @ action toggleCompleted ( id ) { let todo = this . todos . find ( t => t . id === id ) ; const completed = ! todo . completed ; return todosApi . patch ( id , { completed : completed } ) . then ( action ( ( ) => { todo . completed = completed ; } ) ) ; } @ action markAllCompleted ( ) { const markPromises = [ ] ; this . todos . forEach ( todo => { todo . completed = true ; markPromises . push ( todosApi . patch ( todo . id , { completed : todo . completed } ) ) ; } ) ; return Promise . all ( markPromises ) ; } @ action clearCompleted ( ) { const completedTodos = this . todos . filter ( t => t . completed ) ; const removePromises = [ ] ; completedTodos . forEach ( todo => { removePromises . push ( todosApi . remove ( todo . id ) ) ; } ) ; return Promise . all ( completedTodos ) . then ( action ( ( ) => { this . todos = this . todos . filter ( t => ! t . completed ) ; } ) ) ; } }