-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
69 lines (57 loc) · 1.73 KB
/
server.js
File metadata and controls
69 lines (57 loc) · 1.73 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
const path = require('path');
const fs = require('fs/promises');
const express = require('express');
const { fetch } = require('undici');
const app = express();
const PORT = Number(process.env.PORT) || 3000;
const RAW_BASE_URL = 'https://raw.githubusercontent.com/romydias21/contentstack-link-audit/main/public/';
const LATEST_FILE = path.join(__dirname, 'public', 'latest.json');
app.use(express.static(path.join(__dirname, 'public')));
function normalizeBaseUrl(value) {
if (!value) return '';
return value.endsWith('/') ? value : `${value}/`;
}
async function readJsonFile(filePath) {
try {
const data = await fs.readFile(filePath, 'utf-8');
return JSON.parse(data);
} catch (err) {
return null;
}
}
async function fetchRemoteLatest() {
const base = normalizeBaseUrl(RAW_BASE_URL);
const cacheBust = `?t=${Date.now()}`;
const url = `${base}latest.json${cacheBust}`;
try {
const response = await fetch(url, {
headers: {
'User-Agent': 'ContentstackLinkAudit/1.0',
'Cache-Control': 'no-cache'
}
});
if (!response.ok) return null;
return await response.json();
} catch (err) {
return null;
}
}
async function loadLatest() {
const remote = await fetchRemoteLatest();
if (remote) return remote;
return readJsonFile(LATEST_FILE);
}
app.get('/api/health', (req, res) => {
res.json({ status: 'ok', time: new Date().toISOString() });
});
app.get('/api/latest', async (req, res) => {
const payload = await loadLatest();
if (!payload) {
return res.status(404).json({ error: 'No completed run yet' });
}
res.set('Cache-Control', 'no-store');
return res.json(payload);
});
app.listen(PORT, () => {
console.log(`Link audit app running on http://localhost:${PORT}`);
});