-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
76 lines (70 loc) · 2.46 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
var fs = require('fs'),
http = require('http'),
https = require('https'),
url = require('url'),
mongo = require('mongoskin'),
db = mongo.db(process.env.MONGOHQ_URL),
querystring = require('querystring'),
PORT = process.env.PORT || 8090,
BASE_DIR = ".";
db.bind('prices');
http.createServer(
function(req, resp) {
var file = BASE_DIR + req.url;
var contentType;
if (file.match(/html$/)) {
contentType = 'text/html';
} else if (file.match(/js$/)) {
contentType = 'text/javascript';
} else if (file.match(/css$/)) {
contentType = 'text/css';
} else {
contentType = 'text/plain';
}
console.log(file);
if (file.match(/.\/subs/)) {
var query = querystring.parse(file);
search(query, resp);
} else {
fs.readFile(file, function (err, data) {
if (err) {
console.log(err);
resp.writeHeader(500, {"Content-Type": "text/plain"});
resp.write(err + "\n");
resp.end();
} else {
resp.writeHeader(200, {"Content-Type":contentType});
resp.write(data);
resp.end();
}
});
}
}).listen(PORT);
console.log("Server running on port " + PORT);
function search(query, resp) {
var searchKey = {state: 'VIC', boundary:{$exists:true}};
if (query['./subs?type'] == 'house') {
searchKey['house_price'] = {};
if (query['min-price']) {
searchKey['house_price']['$gte'] = query['min-price'] * 1;
}
if (query['max-price']) {
searchKey['house_price']['$lte'] = query['max-price'] * 1;
}
} else {
searchKey['unit_price'] = {};
if (query['min-price']) {
searchKey['unit_price']['$gte'] = query['min-price'] * 1;
}
if (query['max-price']) {
searchKey['unit_price']['$lte'] = query['max-price'] * 1;
}
}
db.prices.find(searchKey).toArray(function(err, subs){
if (subs) {
resp.writeHeader(200, {"Content-Type": "text/plain"});
resp.write(JSON.stringify(subs));
resp.end();
}
});
}