This repository has been archived by the owner on Feb 3, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathposts.js
99 lines (65 loc) · 2.82 KB
/
posts.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
const sqlite3 = require("sqlite3").verbose();
const axios = require("axios");
const path = require("path");
const urlCourses = process.env.CANVAS_API_COURSES_URL;
const meta = {
Authorization: "Bearer " + process.env.CANVAS_TOKEN,
};
const dbPath = path.resolve(__dirname, "./commands/db/memory.db");
module.exports = function () {
//Runned once when server is started
var oneTimeCall = (function () {
var executed = false;
return function () {
if (!executed) {
let db = new sqlite3.Database(dbPath, sqlite3.OPEN_READWRITE, (err) => {
if (err) {
console.error(err.message);
}
console.log("Connected to the memory database.");
});
//get all available courses that can be watched for announcements
axios.get(urlCourses).then(function (response) {
const data = response.data;
const status = response.status;
//check if request is oke
if (status === 200) {
db.serialize(() => {
//drop current table courses so new can be made and it wil always be up to date
db.run(`DROP TABLE courses`, (err, row) => {
if (err) {
console.error(err.message);
}
console.log("Table is dropped!");
});
//Make a new table courses
db.run(`CREATE TABLE courses (course_name TEXT, course_id INTEGER, posted_at REAL, id INTEGER, PRIMARY KEY(id AUTOINCREMENT))`, (err) => {
if (err) {
console.error(err.message);
}
console.log("Table has been succesfully created!");
}
);
data.forEach((element) => {
//Insert data into table courses
//we used DATETIME('now') so it wont error at the very first post of announcements
db.run(`INSERT INTO courses (course_name, course_id, posted_at) VALUES (` + JSON.stringify(element.name) + `,` + element.id + `, DATETIME('now'))`, (err, row) => {
if (err) {
console.error(err.message);
}
console.log("Your records had been pushed to the DB succesfully!");
}
);
});
});
}
})
.catch(function (error) {
console.log(error);
});
executed = true;
}
};
})();
oneTimeCall();
};