-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
142 lines (113 loc) · 3.7 KB
/
server.js
File metadata and controls
142 lines (113 loc) · 3.7 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
import express from 'express';
import path from 'path';
import fs from 'node:fs/promises';
import pkg from 'pg';
const { Pool } = pkg;
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const {
PORT,
STATIC_DIR_REL,
IMAGE_SOURCE_URL,
TEN_MINUTES,
IMAGE_DIR_REL,
OUTPUT_IMAGE_FILENAME,
CACHED_TIME_FILENAME,
} = process.env;
const missingEnvVars = [];
if (!PORT) missingEnvVars.push('PORT');
if (!STATIC_DIR_REL) missingEnvVars.push('STATIC_DIR_REL');
if (!TEN_MINUTES) missingEnvVars.push('TEN_MINUTES');
if (!IMAGE_SOURCE_URL) missingEnvVars.push('IMAGE_SOURCE_URL');
if (!IMAGE_DIR_REL) missingEnvVars.push('IMAGE_DIR_REL');
if (!OUTPUT_IMAGE_FILENAME) missingEnvVars.push('OUTPUT_IMAGE_FILENAME');
if (!CACHED_TIME_FILENAME) missingEnvVars.push('CACHED_TIME_FILENAME');
if (missingEnvVars.length > 0) {
console.error(`❌ Missing environment variables: ${missingEnvVars.join(', ')}`);
process.exit(1);
}
const port = Number(PORT);
const timeoutMs = Number(TEN_MINUTES);
const publicDir = path.join(__dirname, IMAGE_DIR_REL);
const outputPath = path.join(publicDir, OUTPUT_IMAGE_FILENAME);
const cachedTimePath = path.join(publicDir, CACHED_TIME_FILENAME);
async function saveImage(currentTime) {
const response = await fetch(IMAGE_SOURCE_URL);
const buffer = await response.arrayBuffer();
fs.writeFile(outputPath, Buffer.from(buffer));
fs.writeFile(cachedTimePath, currentTime.toISOString());
}
async function dbInitAndConnect() {
var client = null;
console.log('Connecting to db');
try {
client = new Pool({
host: process.env.POSTGRES_HOST,
port: process.env.POSTGRES_PORT,
user: process.env.POSTGRES_USER,
password: process.env.POSTGRES_PASSWORD,
database: process.env.POSTGRES_DB,
})
} catch (e) {
console.log('Error Connecting to db: ', e)
return null;
}
try {
await client.query(` CREATE TABLE IF NOT EXISTS todos (
id BIGSERIAL PRIMARY KEY,
description VARCHAR(140)
)`);
console.log("✅ Table todos check/creation complete.");
} catch (err) {
console.error("❌ Error creating todos:", err);
}
return client;
}
const dbPool = await dbInitAndConnect();
var app = express();
app.use(express.static(path.join(__dirname, STATIC_DIR_REL)));
app.get('/', (req, res, next) => {
if (req.get('User-Agent')?.includes('kube-probe')) {
return res.status(200).send("OK");
}
next();
});
app.get('/healthz', async (_, res) => {
try {
await dbPool.query('SELECT 1');
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end("OK");
} catch (err) {
console.error("Healthcheck DB failed:", err.message);
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end("Error connecting to Db");
}
})
app.get('/getImage', async (_, res) => {
console.log('Chacking image');
try {
var timeText = null;
try {
timeText = await fs.readFile(cachedTimePath, 'utf8');
} catch (e) {
console.log(e)
}
const time = timeText != '' && !!timeText ? new Date(timeText).getTime() : false;
const currentTime = new Date();
if (time) {
if ((currentTime.getTime() - time) > timeoutMs) {
await saveImage(currentTime);
}
} else {
await saveImage(currentTime);
}
res.send();
} catch (e) {
console.log(e);
res.status(500).send();
}
})
app.listen((port), () => {
console.log(`Server started in port ${port}`)
});