forked from BretFisher/node-docker-good-defaults
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
76 lines (63 loc) · 2.17 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// simple node web server that displays hello world
// optimized for Docker image
const express = require('express');
// this example uses express web framework so we know what longer build times
// do and how Dockerfile layer ordering matters. If you mess up Dockerfile ordering
// you'll see long build times on every code change + build. If done correctly,
// code changes should be only a few seconds to build locally due to build cache.
const morgan = require('morgan');
// morgan provides easy logging for express, and by default it logs to stdout
// which is a best practice in Docker. Friends don't let friends code their apps to
// do app logging to files in containers.
const MongoClient = require('mongodb').MongoClient;
// this example includes a connection to MongoDB
const {
MONGO_USERNAME,
MONGO_PASSWORD,
MONGO_HOSTNAME,
MONGO_PORT,
MONGO_DATABASE_NAME
} = process.env;
// Connection URL
const url = `mongodb://${MONGO_USERNAME}:${MONGO_PASSWORD}@${MONGO_HOSTNAME}:${MONGO_PORT}`;
// Create a new MongoClient
const client = new MongoClient(url);
let db;
// Use connect method to connect to the Server
setTimeout(() => {
client.connect(function(err) {
if (err) {
return console.error(err);
}
console.log("Connected successfully to database");
db = client.db(MONGO_DATABASE_NAME);
});
}, 2000);
// Api
const app = express();
app.use(morgan('common'));
app.get('/', function (req, res) {
res.send('Hello Docker World\n');
});
app.get('/healthz', function (req, res) {
// do app logic here to determine if app is truly healthy
// you should return 200 if healthy, and anything else will fail
// if you want, you should be able to restrict this to localhost (include ipv4 and ipv6)
res.send('I am happy and healthy\n');
});
app.get('/documents', function (req, res, next) {
// might have not been connected just yet
if (db) {
db.collection('documents').find({}).toArray(function(err, docs) {
if (err) {
console.error(err);
next(new Error('Error while talking to database'));
} else {
res.json(docs);
}
});
} else {
next(new Error('Waiting for connection to database'));
}
})
module.exports = app;