-
Notifications
You must be signed in to change notification settings - Fork 1
/
web.js
74 lines (61 loc) · 2.25 KB
/
web.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
// web.js
var cors = require('cors');
var express = require('express');
var logfmt = require('logfmt');
var MongoClient = require('mongodb').MongoClient,
format = require('util').format;
var app = express();
function postcode_to_state(postcode) {
if ((postcode >= 2600 && postcode <= 2618) || (String(postcode).substring(0, 2) == '29')) {
return 'Australian Capital Territory';
} else if (String(postcode).charAt(0) == '2') {
return 'New South Wales';
} else if (String(postcode).charAt(0) == '3') {
return 'Victoria';
} else if (String(postcode).charAt(0) == '4') {
return 'Queensland';
} else if (String(postcode).charAt(0) == '5') {
return 'South Australia';
} else if (String(postcode).charAt(0) == '6') {
return 'Western Australia';
} else if (String(postcode).charAt(0) == '7') {
return 'Tasmania';
} else if (String(postcode).charAt(0) == '8' || String(postcode).charAt(0) == '9') {
return 'Northern Territory';
}
};
app.use(cors());
MongoClient.connect(process.env.MONGOHQ_URL, function(err, db) {
if (err) throw err;
var collection = db.collection('legislators');
app.use(logfmt.requestLogger());
app.get('/', function(req, res) {
res.send('hello <br /> /legislators?postcode=4000 <br /> for example.');
});
app.get('/legislators', function(req, res) {
var postcode = req.query.postcode;
if(postcode){
var state = postcode_to_state(postcode);
var senate_docs ="";
collection.find({ state:state, member_type:'senate' }).toArray(function(err, docs) {
senate_docs = docs;
collection.find({ postcodes:postcode, member_type:'house' }).toArray(function(err, docs) {
res.send({
legislators: senate_docs.concat(docs)
});
});
});
} else{
collection.find().toArray(function(err, docs) {
res.send({
legislators: docs
});
});
}
});
console.log(process.env.MONGOHQ_URL);
var port = Number(process.env.PORT || 5000);
app.listen(port, function() {
console.log('Listening on ' + port);
});
});