-
Notifications
You must be signed in to change notification settings - Fork 0
/
habitica.js
116 lines (97 loc) · 2.78 KB
/
habitica.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
"use strict";
const axios = require("axios");
module.exports = class Habitica {
constructor(myAxios, logger = console, sleepMs = 2000) {
this.logger = logger;
this.axios = myAxios;
this.sleepMs = sleepMs;
}
static from(apiUser, apiKey, logger = console) {
const headers = {
["x-api-user"]: apiUser,
["x-api-key"]: apiKey,
};
const baseURL = "https://habitica.com/api/v3/";
const newAxios = axios.create({ headers, baseURL });
return new Habitica(newAxios, logger);
}
async sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async post(url, form) {
await this.sleep(this.sleepMs);
const res = await this.axios.post(url, form);
return res.data;
}
async get(url) {
await this.sleep(this.sleepMs);
const response = await this.axios.get(url);
return response.data;
}
async createTask(task) {
return await this.post(`/tasks/user`, task);
}
async getTask(taskId) {
return await this.get(`/tasks/${taskId}`);
}
async updateTask(task) {
await this.sleep(this.sleepMs);
return await this.axios.put(`/tasks/${task.alias}`, task);
}
async deleteTask(taskId) {
try {
await this.sleep(this.sleepMs);
return await this.axios.delete(`/tasks/${taskId}`);
} catch (err) {
if (err.response.status === 404) {
this.logger.warn("Deleting task that no longer exists", taskId);
} else {
throw err;
}
}
}
async deleteAllTasks(type) {
const tasks = await this.listTasks(type);
await deleteTasks(tasks.map((task) => task._id));
}
async deleteTasks(taskIds) {
for (const taskId of taskIds) {
await this.deleteTask(taskId);
}
}
async listTasks(type = "todos") {
const response = await this.get(
"/tasks/user" + (type ? `?type=${type}` : ""),
);
return response.data;
}
async listDailies() {
return await this.listTasks("dailys");
}
async scoreTask(taskId) {
return await this.post(`/tasks/${taskId}/score/up`);
}
async createChecklistItem(taskId, text) {
this.logger.info(
`Creating checklist item on task ${taskId} with content ${text}`,
);
return await this.post(`/tasks/${taskId}/checklist`, { text });
}
async updateChecklistItem(taskId, itemId, text) {
await this.sleep(this.sleepMs);
return await this.axios.put(`/tasks/${taskId}/checklist/${itemId}`, {
text,
});
}
async deleteChecklistItem(taskId, itemId) {
await this.sleep(this.sleepMs);
return await this.axios.delete(`/tasks/${taskId}/checklist/${itemId}`);
}
async scoreChecklistItem(taskId, itemId) {
try {
await this.post(`/tasks/${taskId}/checklist/${itemId}/score`);
} catch (e) {
throw new Error("failed to score up a task");
}
}
};