This repository was archived by the owner on Oct 24, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
90 lines (67 loc) · 2.04 KB
/
Copy pathapp.js
File metadata and controls
90 lines (67 loc) · 2.04 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
var http = require('http');
var qs = require('querystring');
var MongoClient = require('mongodb').MongoClient;
var config = getConfiguration();
function main(){
http.createServer(function (request, response) {
if(request.method === "GET") {
response.writeHead(200, {'Content-Type': 'text/html'});
getDefaultForm(function(form){
response.end(form);
});
}
if(request.method === "POST") {
var formValues = '';
request.on('data', function(data) {
formValues += data;
});
request.on('end', function() {
var form = qs.parse(formValues);
saveNewMessage(form.message);
console.log('"' + form.message + '" saved!');
getDefaultForm(function(form){
response.end(form);
});
});
}
}).listen(config.port);
console.log('Listening on port: ' + config.port);
};
main();
function saveNewMessage(message){
MongoClient.connect(config.db, function(err, db) {
db.collection("messages").insert({'message':message}, function(err, result) {
db.close();
});
});
}
function getMessages(callback){
MongoClient.connect(config.db, function(err, db) {
db.collection("messages").find().toArray(function(err, result) {
callback(result);
db.close();
});
});
}
function getDefaultForm(callback){
getMessages(function(messages){
var formOutput = '<html><body style="font-family:helvetica">'
+ '<h1>is my docker node app working with mongodb?</h1>'
+ '<form method="post">'
+ '<div><input type="text" id="message" name="message" placeholder="Type your message..." style="width:50%;height:60px;font-size:30px;border:none;"/></div>'
+ '</form><hr/><ul style="list-style:none;">';
for(var i = 0; i < messages.length; i++){
formOutput += '<li>' + messages[i]._id + ' - ' + messages[i].message + '</li>';
}
formOutput += '</ul></body></html>';
callback(formOutput);
});
};
function getConfiguration() {
return {
port: 3000,
db: process.env.NODE_ENV == "production"
? "mongodb://mongo/node-mongo-sample"
: "mongodb://localhost:27017/node-mongo-sample"
};
};