-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
45 lines (37 loc) · 1.35 KB
/
Copy pathindex.js
File metadata and controls
45 lines (37 loc) · 1.35 KB
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
require('dotenv').config();
const express = require('express');
const { fetchStats } = require('./src/fetcher');
const { renderCard } = require('./src/card');
const app = express();
const port = process.env.PORT || 3000;
// In-memory cache with a 1-hour expiration
const cache = new Map();
const CACHE_DURATION_MS = 60 * 60 * 1000; // 1 hour
app.get('/', async (req, res) => {
const username = req.query.username || 'github';
try {
// Check if a valid, non-expired cache entry exists
if (cache.has(username)) {
const cachedData = cache.get(username);
if (Date.now() - cachedData.timestamp < CACHE_DURATION_MS) {
console.log(`Serving response for '${username}' from cache.`);
const card = renderCard(cachedData.stats);
res.setHeader('Content-Type', 'image/svg+xml');
return res.send(card);
}
}
// If no valid cache, fetch new data
console.log(`Fetching new data for '${username}'.`);
const stats = await fetchStats(username);
// Store the new data and timestamp in the cache
cache.set(username, { stats, timestamp: Date.now() });
const card = renderCard(stats);
res.setHeader('Content-Type', 'image/svg+xml');
res.send(card);
} catch (error) {
res.status(500).send(error.message);
}
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});