-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
104 lines (92 loc) · 2.99 KB
/
Copy pathserver.js
File metadata and controls
104 lines (92 loc) · 2.99 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
// Minimal local dev server: serves static files + the /api/tweets endpoint
// backed by the local Postgres database. No login required.
//
// Usage:
// node server.js
// DATABASE_URL=postgresql://... node server.js
//
// Then open http://localhost:8088
const http = require('http');
const fs = require('fs');
const path = require('path');
const { Client } = require('pg');
// Load .env if present (local dev convenience).
try {
const envFile = path.join(__dirname, '.env');
if (fs.existsSync(envFile)) {
for (const line of fs.readFileSync(envFile, 'utf8').split('\n')) {
const m = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*)\s*$/i);
if (m && !process.env[m[1]]) process.env[m[1]] = m[2];
}
}
} catch (_) { /* ignore */ }
const PORT = process.env.PORT || 8088;
const ROOT = __dirname;
const DATABASE_URL = process.env.DATABASE_URL;
if (!DATABASE_URL) {
console.error('ERROR: DATABASE_URL is not set. Copy .env or export it.');
process.exit(1);
}
const client = new Client({ connectionString: DATABASE_URL });
let clientReady = client.connect().then(() => client).catch(err => {
console.error('Failed to connect to Postgres:', err.message);
process.exit(1);
});
const MIME = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.csv': 'text/csv',
'.jpeg': 'image/jpeg',
'.jpg': 'image/jpeg',
'.png': 'image/png',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
};
function serveStatic(req, res) {
let urlPath = decodeURIComponent(req.url.split('?')[0]);
if (urlPath === '/') urlPath = '/index.html';
// Prevent path traversal.
const filePath = path.join(ROOT, urlPath);
if (!filePath.startsWith(ROOT)) {
res.writeHead(403).end('Forbidden');
return;
}
fs.stat(filePath, (err, stat) => {
if (err || !stat.isFile()) {
res.writeHead(404, { 'Content-Type': 'text/plain' }).end('Not found');
return;
}
const ext = path.extname(filePath).toLowerCase();
res.writeHead(200, { 'Content-Type': MIME[ext] || 'application/octet-stream' });
fs.createReadStream(filePath).pipe(res);
});
}
async function serveTweets(res) {
try {
const db = await clientReady;
const result = await db.query(
'SELECT area, tweet, url FROM tweets WHERE area IS NOT NULL AND tweet IS NOT NULL ORDER BY id'
);
res.writeHead(200, {
'Content-Type': 'application/json',
'Cache-Control': 'public, max-age=300, must-revalidate',
});
res.end(JSON.stringify(result.rows));
} catch (err) {
console.error('Failed to load tweets:', err);
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Could not load tweet data.' }));
}
}
const server = http.createServer(async (req, res) => {
if (req.url.split('?')[0] === '/api/tweets') {
return serveTweets(res);
}
serveStatic(req, res);
});
server.listen(PORT, () => {
console.log(`Reform Exposed site running at http://localhost:${PORT}`);
});