The Service
The service class is there to handle all the logic. This allow us to properly have a decoupling between the UI and the logic.
The Service Class
- TodoService.ts
// Imports the services from the Lake
import { rippleServices } from "./Lake";
// Extract the updateTasks function from the services
const { updateTasks } = rippleServices;
/**
* TodoService class
*/
class TodoService {
// We save one instance of the updater function
constructor(protected update = updateTasks()) { }
/**
* Adds a new task to the todo list
* @param text - The text of the task to add
*/
addTask(text: string) {
this.update((tasks) => {
tasks.todo.push({ id: Math.random().toString(36).substring(2, 9), text });
});
}
/**
* Moves a task from the todo list to the done list
* @param id - The id of the task to finish
*/
finishTask(id: string) {
this.update((tasks) => {
const index = tasks.todo.findIndex((task) => task.id === id);
if (index !== -1) {
const task = tasks.todo.splice(index, 1)[0];
tasks.todo = tasks.todo.filter((task) => task.id !== id);
tasks.done.push(task);
}
});
}
/**
* Removes a task from the done list
* @param id - The id of the task to remove
*/
removeTask(id: string) {
this.update((tasks) => {
const index = tasks.done.findIndex((task) => task.id === id);
if (index !== -1) {
tasks.done = tasks.done.filter((task) => task.id !== id);
}
});
}
/**
* Resets the todo list
*/
reset() {
this.update(_ => "reset");
}
}
export const todoService = new TodoService();