-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathindex.js
56 lines (46 loc) · 1.32 KB
/
index.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
const express = require('express');
const axios = require('axios');
const cors = require('cors');
const app = express();
app.use(cors());
app.get('/representatives/:state',
findRepresentativesByState,
jsonResponse
);
app.get('/senators/:state',
findSenatorsByState,
jsonResponse
);
async function findRepresentativesByState(req, res, next) {
const url = `http://whoismyrepresentative.com/getall_reps_bystate.php?state=${req.params.state}&output=json`;
axios.get(url).then(handleApiResponse(res, next));
}
function findSenatorsByState(req, res, next) {
const url = `http://whoismyrepresentative.com/getall_sens_bystate.php?state=${req.params.state}&output=json`;
axios.get(url).then(handleApiResponse(res, next)).catch(handleApiError(res, next));
}
function handleApiResponse(res, next) {
return (response) => {
res.locals = {
success: true,
results: response.data.results
};
return next();
};
}
function jsonResponse(req, res, next) {
return res.json(res.locals);
}
function handleApiError(res, next) {
return (err) => {
res.locals = {
success: false,
error: err || 'Invalid request. Please check your state variable.'
};
return next();
};
}
const port = process.env.PORT ?? 3000;
app.listen(port, () => {
console.log('API listening at http://localhost:%s', port);
});