-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
56 lines (46 loc) · 1.17 KB
/
index.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
import fastify from 'fastify';
import { DateTime } from 'luxon';
import { fetchAndParseXML, print } from './utils.js';
const server = fastify();
let programs = null;
async function updatePrograms() {
programs = await fetchAndParseXML();
}
async function getProgramsOfTheDay(json = false) {
const DATE = DateTime.local().setZone('Europe/Paris');
const TODAY = DATE.toISODate();
const TOMORROW = DATE.plus({ days: 1 }).toISODate();
if (!programs[TODAY]) {
programs = await fetchAndParseXML();
}
if (!programs[TOMORROW]) {
updatePrograms();
}
if (json) {
return programs[TODAY];
}
return print(programs[TODAY]);
}
server.get('/', async () => {
const data = await getProgramsOfTheDay();
return data;
});
server.get('/json', async () => {
const data = await getProgramsOfTheDay(true);
return data;
});
server.get('/fetch', async () => {
updatePrograms();
return { updating: true };
});
const start = async () => {
try {
await server.listen({ port: 3000, host: '0.0.0.0' });
console.log('API started ✓');
updatePrograms();
} catch (error) {
console.log('Error starting the API', error);
process.exit(1);
}
};
start();