-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
97 lines (78 loc) · 2.67 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
var restify = require("restify");
var mongojs = require("mongojs");
var ip_addr = "127.0.0.1";
var port = "8080";
var server = restify.createServer({
name : "geotrashAPI"
});
var connection_string = '127.0.0.1:27017/geotrashdb';
var db = mongojs(connection_string, ['geotrashdb']);
var trash = db.collection("trash");
server.use(restify.queryParser());
server.use(restify.bodyParser());
server.use(restify.CORS());
function findAllTrash(req, res , next){
res.setHeader('Access-Control-Allow-Origin','*');
trash.find().limit(20).sort({postedOn : -1} , function(err , success){
console.log('Response success '+success);
console.log('Response error '+err);
if(success){
res.send(200 , success);
return next();
}else{
return next(err);
}
});
}
function findTrashNear(req, res , next){
res.setHeader('Access-Control-Allow-Origin','*');
console.log('findTrash');
trash.find({loc: {$near: [req.query.longitude, req.query.latitude], $maxDistance: req.query.distance}}, function(err, success){
console.log(req.query.distance);
console.log('Response success '+success);
console.log('Response error '+err);
if(success){
res.send(200 , success);
return next();
}
return next(err);
});
}
function postNewTrash(req , res , next){
var newTrash = {};
newTrash.name = req.params.name;
newTrash.description = req.params.description;
newTrash.loc = [req.params.longitude, req.params.latitude];
newTrash.postedOn = new Date();
res.setHeader('Access-Control-Allow-Origin','*');
trash.save(newTrash , function(err , success){
console.log('Response success '+success);
console.log('Response error '+err);
if(success){
res.send(201 , newTrash);
return next();
}else{
return next(err);
}
});
}
function deleteTrash(req , res , next){
res.setHeader('Access-Control-Allow-Origin','*');
trash.remove({_id:mongojs.ObjectId(req.params.trashId)} , function(err , success){
console.log('Response success '+success);
console.log('Response error '+err);
if(success){
res.send(204);
return next();
} else{
return next(err);
}
})
}
var PATH = '/trash'
server.get({path : PATH +'/near', version : '0.0.1'} , findTrashNear);
server.post({path : PATH , version: '0.0.1'} ,postNewTrash);
server.del({path : PATH +'/:trashId' , version: '0.0.1'} ,deleteTrash);
server.listen(port, ip_addr, function () {
console.log("%s listening at %s", server.name, server.url);
});