-
Notifications
You must be signed in to change notification settings - Fork 6
/
app.js
83 lines (72 loc) · 2.26 KB
/
app.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
81
82
if(process.env.VCAP_SERVICES){
var env = JSON.parse(process.env.VCAP_SERVICES);
var mongo = env['mongodb-1.8'][0]['credentials'];
}
else{
var mongo = {
"hostname":"localhost",
"port":27017,
"username":"",
"password":"",
"name":"",
"db":""
}
}
var generate_mongo_url = function(obj){
obj.hostname = (obj.hostname || 'localhost');
obj.port = (obj.port || 27017);
obj.db = (obj.db || 'test');
if(obj.username && obj.password){
return "mongodb://" + obj.username + ":" + obj.password + "@" + obj.hostname + ":" + obj.port + "/" + obj.db;
}
else{
return "mongodb://" + obj.hostname + ":" + obj.port + "/" + obj.db;
}
}
var mongourl = generate_mongo_url(mongo);
/* Http Variables */
var port = (process.env.VMC_APP_PORT || 3000);
var host = (process.env.VCAP_APP_HOST || 'localhost');
var http = require('http');
var record_visit = function(req, res){
/* Connect to the DB and auth */
require('mongodb').connect(mongourl, function(err, conn){
conn.collection('ips', function(err, coll){
/* Simple object to insert: ip address and date */
object_to_insert = { 'ip': req.connection.remoteAddress, 'ts': new Date() };
/* Insert the object then print in response */
/* Note the _id has been created */
coll.insert( object_to_insert, {safe:true}, function(err){
if(err) { console.log(err.stack); }
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write(JSON.stringify(object_to_insert));
res.end('\n');
});
});
});
}
var print_visits = function(req, res){
/* Connect to the DB and auth */
require('mongodb').connect(mongourl, function(err, conn){
conn.collection('ips', function(err, coll){
coll.find({}, {limit:10, sort:[['_id','desc']]}, function(err, cursor){
cursor.toArray(function(err, items){
res.writeHead(200, {'Content-Type': 'text/plain'});
for(i=0; i<items.length;i++){
res.write(JSON.stringify(items[i]) + "\n");
}
res.end();
});
});
});
});
}
http.createServer(function (req, res) {
params = require('url').parse(req.url);
if(params.pathname === '/history') {
print_visits(req, res);
}
else{
record_visit(req, res);
}
}).listen(port, host);