-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
75 lines (68 loc) · 2.04 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
74
75
const { json, send } = require("micro");
const limitedMap = require("limited-map");
const query = require("micro-query");
const { FileTileSet, S3TileSet } = require("./tileset");
const cacheSize = process.env.TILE_SET_CACHE || 128;
const tileFolder = process.env.TILE_SET_PATH || __dirname;
const maxPostSize = process.env.MAX_POST_SIZE || "500kb";
const maxParallelProcessing = 500;
const tiles = tileFolder.startsWith("s3://")
? new S3TileSet({ cacheSize })
: new FileTileSet(tileFolder, { cacheSize });
async function handlePOST(req, res) {
const payload = await json(req, { limit: maxPostSize });
if (
!payload ||
!Array.isArray(payload) ||
!payload.every(([lat, lng]) => Number.isFinite(lat) && Number.isFinite(lng))
) {
return send(res, 400, {
error:
"Invalid Payload. Expected a JSON array with latitude-longitude pairs: [[lat, lng], ...]"
});
}
const result = await limitedMap(
payload,
ll => tiles.getElevation(ll),
maxParallelProcessing
);
return result;
}
async function handleGET(req, res) {
const reqQuery = query(req);
const lat = parseFloat(reqQuery.lat);
const lng = parseFloat(reqQuery.lng);
if (lat == null || !Number.isFinite(lat)) {
return send(res, 400, {
error:
"Invalid Latitude. Expected a float number as query parameter: ?lat=12.3&lng=45.6"
});
}
if (lng == null || !Number.isFinite(lng)) {
return send(res, 400, {
error:
"Invalid Longitude. Expected a float number as query parameter: ?lat=12.3&lng=45.6"
});
}
const result = await tiles.getElevation([lat, lng]);
return result;
}
async function handleGETStatus(req, res) {
return send(res, 200);
}
module.exports = async (req, res) => {
if (req.method == "GET" && req.url == "/status") {
return handleGETStatus(req, res);
}
else
{
switch (req.method) {
case "POST":
return handlePOST(req, res);
case "GET":
return handleGET(req, res);
default:
return send(res, 405, { error: "Only GET or POST allowed" });
}
}
};