-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
91 lines (71 loc) · 2.49 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
81
82
83
84
85
86
87
88
89
90
91
//includes
var express = require('express');
var app = express.createServer();
var config = require('./conf/config');
var DbManager = require('./lib/DbManager').DbManager;
var util = require('util');
//create a new connection
var db = new DbManager(config.db);
//Configure app
app.configure(function(){
app.set('views', __dirname + '/public/views');
app.set('view engine', 'jade');
app.set('view options', {layout:false})
app.register('.html', require('jade'));
});
//Main application processing
app.get('/', function(req, res){
res.render('index.html');
});
//postcode routing
app.all('/postcode/:postcode.:format?', function(req, res){
//extrct params
format = req.params.format;
postcode = req.params.postcode.replace(/ /gi, '').toUpperCase();
if(postcode){
console.log("Fetching: " + postcode);
switch(format){
case 'xml':
res.contentType('application/xml');
break;
case 'csv':
res.contentType('application/csv');
break;
case 'json':
default:
res.contentType('application/json');
db.getDoc('postcode', {"postcode": postcode}, function(err, doc, live_collection){
if(err) throw err;
console.log(doc);
res.json(doc, 200);
});
break;
}
}else{
next();
}
});
//postcode near routing
app.all('/postcode/near/:postcode/:limit?', function(req, res){
//extrct params
limit = (req.params.limit)? { limit: req.params.limit } : {} ;
postcode = req.params.postcode.replace(/ /gi, '').toUpperCase();
db.getDoc('postcode', {"postcode": postcode}, function(err, doc, live_collection){
if(err) throw err;
//Create search
center = [ doc.loc.lon , doc.loc.lat ];
radius = 1; //Within 1 degree
newSearch = {"loc" : {"$within" : {"$center" : [center, radius]}}}
live_collection.find(newSearch, limit).toArray(function(err, docs) {
if(err) throw err;
obj = { postcodes : docs } ;
res.json(obj, 200);
});
});
});
//pickup any rogue requests
app.get('*', function(req,res){
res.send('Error: please request http://postcode.nodester.com/postcode/[postcode].[json|xml|csv]', 404);
});
//bind server port
app.listen(config.http.port);