-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtodoRepository.js
47 lines (40 loc) · 1.1 KB
/
todoRepository.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
import fs from 'fs';
export function getAllTodos() {
const todos = readDatabase().todos;
return todos;
}
/**
* Returns the todo with the given ID
* @param {number} id
* @returns the todo
*/
export function getTodo(id) {
const todo = getAllTodos().find(t => t.id === +id)
return todo
}
export function createTodo(todo) {
todo.id = Math.max(...getAllTodos().map(t => t.id)) + 1;
todo.complete = false;
const todos = [...getAllTodos(), todo];
saveDatabase({ ...readDatabase(), todos });
return todo;
}
/**
* Makes a completed todo uncompleted and vice-versa.
* @param {number} id
* @returns The new todo
*/
export function toggleTodoComplete(id) {
const todo = getAllTodos().find(t => t.id === +id)
todo.complete = !todo.complete;
const todos = [...getAllTodos().filter(todo => todo.id !== +id), todo];
saveDatabase({ ...readDatabase(), todos });
return todo;
}
const databaseFile = "./database.json";
const readDatabase = () =>
JSON.parse(fs.readFileSync(databaseFile))
const saveDatabase = (data) => {
const str = JSON.stringify(data)
fs.writeFileSync(databaseFile, str);
}