-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
58 lines (49 loc) · 1.7 KB
/
index.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
require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const port = process.env.PORT || 3000;
// MongoDB connection URI from environment variable
const mongoURI = process.env.DATABASE_URI;
let dbConnectionSuccessful = false;
// Connect to MongoDB
mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
console.log('MongoDB connected');
dbConnectionSuccessful = true;
})
.catch(err => {
console.log('Error connecting to MongoDB:', err);
dbConnectionSuccessful = false;
});
// Define a schema for the health-test collection
const healthSchema = new mongoose.Schema({
name: String,
up: Boolean,
});
// Create a model for the health-test collection
const HealthTest = mongoose.model('health-test', healthSchema);
// Define the /check endpoint
app.get('/health', async (req, res) => {
if (!dbConnectionSuccessful) {
res.status(200).send('Service is up (no database connection)');
return;
}
try {
let healthCheck = await HealthTest.findOne({ name: 'health-check' });
if (!healthCheck) {
healthCheck = new HealthTest({ name: 'health-check', up: true });
await healthCheck.save();
res.status(200).send('Service is up and document was created');
} else if (healthCheck.up) {
res.status(200).send('Service is up');
} else {
res.status(500).send('Service is down');
}
} catch (error) {
res.status(500).send('Error checking health status');
}
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});