forked from busbud/coding-challenge-backend-c
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
65 lines (50 loc) · 1.62 KB
/
Copy pathapp.js
File metadata and controls
65 lines (50 loc) · 1.62 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
const express = require('express');
const ev = require('express-validator');
const port = process.env.PORT || 2345;
const cities = require('./lib/cities');
const app = express();
app.use(ev());
app.use(express.static('public'));
app.get("/", function(req, res) {
res.sendfile('./public/index.html');
});
app.get("/suggestions", function(req, res) {
req.check('q', "Must be alphabetic only with whitespace and dashes or dot.").notEmpty().isAscii;
req.check('q', "Must be at least 2 chars before the autocomplete works.").isLength({min: 2});
if(req.query.lat != undefined) {
req.check('lat', "Must be a valid coordinate (latitude).").isFloat();
}
if(req.query.long != undefined) {
req.check('long', "Must be a valid coordinate (longitude).").isFloat();
}
var errors = req.validationErrors(true);
if(errors) {
res.status(404).json({
errors: errors,
suggestions: []
});
return;
}
var search = req.query.q;
var latitude = req.query.lat ? req.query.lat : null;
var longitude = req.query.long ? req.query.long : null;
cities.search({ q: search.toLowerCase(), lat: latitude, long: longitude }, function(data) {
if (data.length == 0) {
res.status(404).json({
errors: "Nothing was found",
suggestions: []
});
return;
}
data.sort(function(a, b) {
return b.finalScore < a.finalScore ? -1 : b.finalScore > a.finalScore ? 1 : 0;
});
res.status(200).json({
suggestions: data
});
});
});
app.listen(port, function() {
console.log('Server running at http://127.0.0.1:%d/suggestions', port);
});
module.exports = app;