forked from oktadev/okta-nodejs-aws-lambda-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwhere-is-it.js
72 lines (61 loc) · 2.21 KB
/
where-is-it.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
const topojson = require('topojson-client');
const pointInPolygon = require('@turf/boolean-point-in-polygon').default;
const { point } = require('@turf/helpers');
const fetch = require('node-fetch');
const getCountries = () => fetch('https://raw.githubusercontent.com/johan/world.geo.json/34c96bba9c07d2ceb30696c599bb51a5b939b20f/countries.geo.json')
.then(response => response.json());
const getUSZipCodes = () => fetch('https://gist.githubusercontent.com/jefffriesen/6892860/raw/e1f82336dde8de0539a7bac7b8bc60a23d0ad788/zips_us_topo.json')
.then(response => response.json())
.then(us => topojson.feature(us, us.objects.zip_codes_for_the_usa));
const cleanInput = value => {
const num = Number(value);
return num || num === 0 ? num : '';
};
const input = ({ name, value }) => `
<input
autofocus
required
type="number"
placeholder="Longitude"
name="${name}"
value="${value}"
step="0.0000001"
/>
`;
module.exports = async (req, res) => {
const lng = cleanInput(req.query.lng);
const lat = cleanInput(req.query.lat);
let payload = '';
if (lng !== '' && lat !== '') {
const countries = await getCountries();
const location = point([lng, lat]);
const findFeature = feature => pointInPolygon(location, feature);
const country = countries.features.find(findFeature);
payload = {
lng,
lat,
country: country ? country.properties.name : '🤷',
};
if (country && country.id === 'USA') {
const zipcodes = await getUSZipCodes();
const zipcode = zipcodes.features.find(findFeature);
if (zipcode) {
const { name: city, zip, state } = zipcode.properties;
Object.assign(payload, { city, state, zip });
}
}
}
if ((req.headers.accept || '').split(',').includes('application/json')) {
res.json(payload || { error: "You must include `lng` and `lat` url params" });
} else {
res.send(`
<h2>Enter some coordinates to find out more about the location</h2>
<form method="get">
${input({ name: 'lng', value: lng })}
${input({ name: 'lat', value: lat })}
<button type="submit">Where is it?</button>
</form>
<pre>${payload && JSON.stringify(payload, null, 2)}</pre>
`);
}
};