Created
September 15, 2019 04:01
-
-
Save adash333/c3dd83702c4073bd4a9b07137c02c643 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { set, get } from "./storage"; | |
import { Todo } from "../interfaces/todo"; | |
class todosServiceController { | |
public todos: Todo[]; | |
async load(): Promise<Todo[]> { | |
if (this.todos) { | |
return this.todos; | |
} else { | |
this.todos = (await get("todos")) || []; | |
return this.todos; | |
} | |
} | |
async save(): Promise<void> { | |
return await set("todos", this.todos); | |
} | |
getTodo(id): Todo { | |
return this.todos.find(Todo => Todo.id === id); | |
} | |
createTodo(title): void { | |
// Create a unique id that is one larger than the current largest id | |
let id = Math.max(...this.todos.map(Todo => parseInt(Todo.id)), 0) + 1; | |
this.todos.push({ | |
id: id.toString(), | |
title: title, | |
content: "" | |
}); | |
this.save(); | |
} | |
updateTodo(Todo, content): void { | |
// Get the index in the array of the Todo that was passed in | |
let index = this.todos.indexOf(Todo); | |
this.todos[index].content = content; | |
this.save(); | |
} | |
deleteTodo(Todo): void { | |
// Get the index in the array of the Todo that was passed in | |
let index = this.todos.indexOf(Todo); | |
// Delete that element of the array and resave the data | |
if (index > -1) { | |
this.todos.splice(index, 1); | |
this.save(); | |
} | |
} | |
} | |
export const todosService = new todosServiceController(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment