-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
76 lines (59 loc) · 2.34 KB
/
app.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
import axios from 'axios';
import express from 'express';
import cron from 'node-cron';
import { connectToRedis, getCache, setCache } from './redis.js';
const app = express();
const port = process.env.PORT || 3000;
import dotenv from 'dotenv';
dotenv.config();
const fetchDataFromApi = async () => {
const apiURL = `https://clist.by:443/api/v4/contest/?username=${process.env.USER_NAME}&api_key=${process.env.API_KEY}&?limit=30&total_count=false&with_problems=false&upcoming=true&format_time=true&filtered=true&order_by=start`;
try {
const apiResponse = await axios.get(apiURL);
const freshData = apiResponse.data;
await setCache(apiURL, freshData);
console.log('Data refreshed successfully.');
return freshData;
} catch (error) {
console.error('Error fetching data from URL:', error);
return null;
}
};
const cronJob = cron.schedule('*/30 * * * *', async () => {
console.log('Data refresh started at:', new Date().toLocaleString());
try {
console.log('Refreshing data...');
await fetchDataFromApi();
console.log('Data refresh completed successfully at:', new Date().toLocaleString());
} catch (error) {
console.error('Error during data refresh:', error);
}
});
app.use(async (req, res, next) => {
const cacheKey = `https://clist.by:443/api/v4/contest/?username=${process.env.USER_NAME}&api_key=${process.env.API_KEY}&?limit=30&total_count=false&with_problems=false&upcoming=true&format_time=true&filtered=true&order_by=start`;
const cachedData = await getCache(cacheKey);
if (cachedData) {
res.send(JSON.parse(cachedData));
} else {
try {
const freshData = await fetchDataFromApi();
if (freshData) {
await setCache(cacheKey, freshData);
res.send(freshData);
} else {
res.status(500).send('Internal Server Error');
}
} catch (error) {
console.error('Error during middleware execution:', error);
res.status(500).send('Internal Server Error');
}
}
});
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something went wrong!');
});
app.listen(port, async () => {
await connectToRedis();
console.log(`Server is running on port ${port}`);
});