-
Notifications
You must be signed in to change notification settings - Fork 7
/
server.js
80 lines (61 loc) · 2.19 KB
/
server.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
77
78
79
80
let express = require('express');
let path = require('path');
let fs = require('fs');
let MongoClient = require('mongodb').MongoClient;
let bodyParser = require('body-parser');
let app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, "sign-up.html"));
});
app.get('/profile-picture', function (req, res) {
let img = fs.readFileSync(path.join(__dirname, "images/Designing/output-onlinegiftools (1).gif"));
res.writeHead(200, {'Content-Type': 'image/gif' });
res.end(img, 'binary');
});
// use when starting application locally
let mongoUrlLocal = "mongodb://admin:password@localhost:27017";
// use when starting application as docker container
let mongoUrlDocker = "mongodb://admin:password@mongodb";
// pass these options to mongo client connect request to avoid DeprecationWarning for current Server Discovery and Monitoring engine
let mongoClientOptions = { useNewUrlParser: true, useUnifiedTopology: true };
// "user-account" in demo with docker. "my-db" in demo with docker-compose
let databaseName = "my-db";
app.post('/sign-up', function (req, res) {
let userObj = req.body;
MongoClient.connect(mongoUrlLocal, mongoClientOptions, function (err, client) {
if (err) throw err;
let db = client.db(databaseName);
userObj['userid'] = 1;
let myquery = { userid: 1 };
let newvalues = { $set: userObj };
db.collection("users").updateOne(myquery, newvalues, {upsert: true}, function(err, res) {
if (err) throw err;
client.close();
});
});
// Send response
res.send(userObj);
});
app.get('/log-in', function (req, res) {
let response = {};
// Connect to the db
MongoClient.connect(mongoUrlLocal, mongoClientOptions, function (err, client) {
if (err) throw err;
let db = client.db(databaseName);
let myquery = { userid: 1 };
db.collection("users").findOne(myquery, function (err, result) {
if (err) throw err;
response = result;
client.close();
// Send response
res.send(response ? response : {});
});
});
});
app.listen(3000, function () {
console.log("app listening on port 3000!");
});