-
Notifications
You must be signed in to change notification settings - Fork 0
/
task.js
116 lines (89 loc) · 2.72 KB
/
task.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
const fs = require('fs');
const chalk = require('chalk');
/* ADD TASK */
const addTask = (title, description, type) => {
// Lấy danh sách task đã có
const allTasks = fetchTasks();
// Tạo dộng ID
// Tạo đối tượng task
const task = {
id: Math.round(Math.random() * 10000).toString(),
title,
description,
type,
};
// Thêm task vào danh sách
allTasks.push(task);
// Lựu lại danh sách vào file
fs.writeFileSync('task.json', JSON.stringify(allTasks));
console.log(chalk.green('Successfully !'));
};
/* DELETE TASK */
const deleteTask = (id) => {
const allTasks = fetchTasks();
const index = allTasks.findIndex((task) => {
return task.id === id;
});
if (index === -1) {
console.log(chalk.red('Task not found !'));
return
};
allTasks.splice(index, 1);
fs.writeFileSync('task.json', JSON.stringify(allTasks));
console.log(chalk.green('Successfully !'));
}
/* UPDATE TASK */
const updateTask = (id, title, description, type) => {
const allTasks = fetchTasks();
const index = allTasks.findIndex((task) => {
return task.id === id;
});
if (index === -1) {
console.log(chalk.red('Task not found !'));
return;
}
const updatedTask = { id, title, description, type };
allTasks.splice(index, 1, updatedTask);
fs.writeFileSync('task.json', JSON.stringify(allTasks));
};
/* VIEW ALL TASK */
const viewAllTasks = () => {
const allTasks = fetchTasks();
return console.log(chalk.green('allTasks--->'), allTasks);
}
/* VIEW TASK BY DETAIL */
const viewTaskByDetail = (id) => {
const allTasks = fetchTasks();
const taskByID = allTasks.find(task => task.id === id.toString());
if (taskByID) {
console.log(chalk.green('Successfully !'));
console.log(chalk.green('taskByID'), taskByID);
return;
}
console.log(chalk.red('Task not found !'));
}
/* VIEW TASK BY TYPE */
const viewTasksByType = (type) => {
const allTasks = fetchTasks();
const tasksByType = allTasks.filter(task => task.type === type);
if (tasksByType == '') {
console.log(chalk.red('Task not found !'));
return;
};
console.log(chalk.green('Successfully !'));
console.log(chalk.green('tasksByType'), tasksByType);
}
/* FETCH TASK */
const fetchTasks = () => {
try {
const buffer = fs.readFileSync('./task.json');
console.log('buffer --->', buffer);
const tasksJSON = buffer.toString();
return JSON.parse(tasksJSON);
} catch (error) {
return [];
}
};
module.exports = {
addTask, deleteTask, updateTask, viewAllTasks, viewTaskByDetail, viewTasksByType
}