-
Notifications
You must be signed in to change notification settings - Fork 10
/
index.js
73 lines (63 loc) · 1.86 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
const express = require('express');
const fetch = require('node-fetch');
const cheerio = require('cheerio');
const _ = require('lodash');
const app = express();
const { PORT = 3000 } = process.env;
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept',
);
next();
});
app.get('/:city', async (req, res) => {
const city = _.words(_.startCase(req.params.city)).join('-');
const currency = Object.keys(req.query)[0] ? Object.keys(req.query)[0] : 'CAD';
const response = await fetch(
`https://www.numbeo.com/cost-of-living/in/${city}?displayCurrency=${currency}`,
);
if (!response.ok) {
return res.status(response.status).send(response.statusText);
}
const html = await response.text();
const $ = cheerio.load(html);
const rows = $('body > div.innerWidth > table > tbody > tr')
.filter((i, el) => $(el).children('td').length === 3)
.map((i, el) =>
$(el)
.children()
.map((i, el) => $(el).text().trim())
.toArray(),
)
.toArray();
const costs = chunkArray(rows, 3).map(([item, costWithSymbol, range]) => {
const cost = costWithSymbol.replace(/^.*?([\d,.]+).*?$/, '$1');
const [rangeLow, rangeHigh] = range.split('-');
return {
item,
cost,
range: {
low: rangeLow,
high: rangeHigh,
},
};
});
return res.json({ city, currency, costs });
});
app.get('*', (req, res) =>
res.status(400).json({
error: 'No city supplied. Please navigate to `/:city` to obtain results.',
}),
);
function chunkArray(arr, chunkSize) {
let temp = [];
for (let i = 0; i < arr.length; i += chunkSize) {
temp.push(arr.slice(i, i + chunkSize));
}
return temp;
}
app.listen(PORT, () =>
console.log(`Cost of Living API running on port ${PORT}`),
);