forked from i-am-alice/2nd-devs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtodoist.ts
executable file
·80 lines (68 loc) · 2.39 KB
/
todoist.ts
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
import {ITask, ITaskClose, ITaskModify} from "./todoist.dt";
const apiCall = async (endpoint = '/me', method = 'GET', body = {}) => {
try {
const response = await fetch(`https://api.todoist.com/rest/v2${endpoint}`, {
method,
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.TODOIST_API_KEY}`
},
body: method === 'POST' ? JSON.stringify(body) : undefined,
});
return response.status === 204 ? true : await response.json();
} catch (err) {
console.log(err);
}
}
export const listUncompleted = async (): Promise<ITask[]> => {
const uncompleted = await apiCall('/tasks', 'GET');
return uncompleted.map((task: ITask) => {
return {
id: task.id,
content: task.content,
due: task.due ? task.due.string : undefined,
}
});
}
export const addTasks = async (tasks: ITaskModify[]): Promise<ITaskModify[]> => {
const promises = tasks.map(task =>
apiCall('/tasks', 'POST', {
content: task.content,
due_string: task.due_string
})
);
const addedTasks = await Promise.all(promises);
return addedTasks.map(addedTask => ({
id: addedTask.id,
content: addedTask.content,
due_string: addedTask.due ? addedTask.due.string : null,
}));
}
export const updateTasks = async (tasks: ITaskModify[]): Promise<ITaskModify[]> => {
const promises = tasks.map((task) =>
apiCall(`/tasks/${task.id}`, 'POST', {
content: task.content,
due_string: task.due_string,
is_completed: task.is_completed
})
);
const updatedTasks = await Promise.all(promises);
return updatedTasks.map(updatedTask => ({
id: updatedTask.id,
content: updatedTask.content,
due_string: updatedTask.due ? updatedTask.due.string : undefined,
}));
}
export const closeTasks = async (tasks: ITaskClose[]): Promise<{[key: string]: 'completed'}[] | string> => {
const promises = tasks.map((id) =>
apiCall(`/tasks/${id}/close`, 'POST')
);
try {
await Promise.all(promises);
return tasks.map(closedTask => ({
[closedTask.toString()]: 'completed',
}));
} catch (e) {
return 'No tasks were closed (maybe they were already closed)';
}
}