-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtodoController.js
68 lines (62 loc) · 1.43 KB
/
todoController.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
let todos = require("./data");
const findAll = () => {
return new Promise((resolve, reject) => {
resolve(todos);
});
};
const findById = (id) => {
return new Promise((resolve, reject) => {
const todo = todos.find((todo) => todo.id === id);
if (todo) {
resolve(todo);
} else {
reject(`Todo with id${id} not found!`);
}
});
};
const deleteById = (id) => {
return new Promise((resolve, reject) => {
const newTodos = todos.filter((todo) => todo.id !== id);
todos = [...newTodos];
resolve({ message: "Todo deleted successfully!!" });
});
};
const create = (todo) => {
return new Promise((resolve, reject) => {
const newTodo = {
id: Date.now().toString(),
...todo,
};
todos = [newTodo, ...todos];
resolve(newTodo);
});
};
const updateById = async (id, body) => {
try {
const { title, description } = body;
const todo = await findById(id);
if (!todo) {
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ message: "Todo not found!" }));
}
return new Promise((resolve, reject) => {
const updatedTodo = {
id,
title: title ? title : todo.title,
description: description ? description : todo.description,
};
const index = todos.findIndex((todo) => todo.id === id);
todos[index] = updatedTodo;
resolve(updatedTodo);
});
} catch (error) {
console.log(error);
}
};
module.exports = {
findAll,
findById,
deleteById,
create,
updateById,
};