-
Notifications
You must be signed in to change notification settings - Fork 0
/
APIScheduler.js
55 lines (43 loc) · 1.58 KB
/
APIScheduler.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
var scheduler = require("node-schedule");
const schedule = require("node-schedule");
const axios = require("axios");
const mongoose = require("mongoose");
var modUpdateJob = schedule.scheduleJob("0 0 * * *", () => {
console.log("Checking for new modules...");
const AY = new Date().getFullYear();
axios.get(`https://api.nusmods.com/v2/${AY - 1}-${AY}/moduleList.json`).then((apiRes) => {
const apiMods = apiRes.data.map((module) => {
return `${module.moduleCode} - ${module.title}`;
});
const backendURL =
process.env.NODE_ENV !== "production"
? "http://localhost:5000/backend"
: "https://cheato.herokuapp.com/backend";
axios
.get(`${backendURL}/schools/NUS`)
.then((nusRes) => {
const nusId = nusRes.data._id;
axios.get(`${backendURL}/modules`).then((currentRes) => {
const backendMods = currentRes.data.map((module) => module.name);
const absentMods = apiMods
.filter((module) => backendMods.indexOf(module) === -1)
.map((module) => {
return { school: mongoose.Types.ObjectId(nusId), name: module };
});
console.log(`${absentMods.length} new modules found..`);
// If there is, post it as new mods into mongo
if (absentMods.length > 0) {
axios
.post(`${backendURL}/modules`, absentMods)
.then((res) => {
console.log(`${res.data.newMods.length} added!`);
})
.catch((err) => console.log(`${err.name} - ${err.message}`));
}
});
})
.catch((err) => console.log(`${err.name} - ${err.message}`));
});
});
console.log("Job scheduled");
module.exports = modUpdateJob;