-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.js
More file actions
executable file
·70 lines (55 loc) · 1.76 KB
/
app.js
File metadata and controls
executable file
·70 lines (55 loc) · 1.76 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
/**
* Created by samiyuru on 5/5/14.
*/
var express = require('express');
var mongodb = require('mongodb');
var app = express();
app.use('/', express.static('./public'));
mongodb.MongoClient.connect("mongodb://localhost/chatdb", function(err, db){
if(err) throw err;
app.post('/msg', function(req, res){
var msgObj = {
sender: req.query.sender,
text:req.query.text,
time: new Date().getTime()
};
var msgsCol = db.collection('msgs');
msgsCol.insert(msgObj, function(err, docs){
if(err){
res.json({err:"failed to save the message"});
}else{
res.json({success:true, data:docs[0]});
}
});
});
app.get('/msg', function(req, res){
var me = req.query.me, time = parseInt(req.query.time);
if(time == 0){
res.json({success:true, data:[], lTime:new Date().getTime()});
}else{
var msgsCol = db.collection('msgs');
msgsCol.find({
sender:{
$ne:me
},
time:{
$gt:time
}
}).sort({time:1}).toArray(function(err, docs){
if(err){
res.json({err:"could not fetch messages"});
}else{
res.json({
success:true,
data:docs,
lTime:(docs.length == 0)?time:docs[docs.length - 1].time
});
}
});
}
var msgsCol = db.collection('msgs');
});
app.listen(3000, function(){
console.log("server started . . .");
});
});