-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
56 lines (45 loc) · 1.49 KB
/
Copy pathindex.js
File metadata and controls
56 lines (45 loc) · 1.49 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
// imports
const express = require('express'),
constituency = require('./lib/constituency'),
{ Constituency } = require('./lib/database');
// config
const port = 3000,
validPostcodes =
/^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$/,
validLatitudes = /^[56]\d(\.\d+)?$/,
validLongitudes = /^-?[012](\.\d+)?$/;
// create server
const app = express();
// serve static files
app.use(express.static('static'));
// get information for a postcode
app.get('/api/:postcode', (req, res) => {
let { postcode } = req.params;
postcode = postcode.toUpperCase();
if (!validPostcodes.test(postcode)) {
res.sendStatus(400);
return;
}
constituency.byPostcode(postcode)
.then(code => res.send((new Constituency(code)).json))
.catch(error => {
console.log(`[ERROR] ${error}`);
res.sendStatus(500);
});
});
// get information for a set of coordinates
app.get('/api/:latitude/:longitude/', (req, res) => {
const { latitude, longitude } = req.params;
if (!validLatitudes.test(latitude) || !validLongitudes.test(longitude)) {
res.sendStatus(400);
return;
}
constituency.byCoordinates(latitude, longitude)
.then(code => res.send((new Constituency(code)).json))
.catch(error => {
console.error(`[ERROR] ${error}`);
res.sendStatus(500);
});
});
// listen for requests
app.listen(port, () => console.log(`how-many-votes listening on port ${port}!`));