Files

61 lines
2.4 KiB
JavaScript

// Google Maps page: thin client over /google/maps/*. Every Google call is a
// POST and a dry run until "Call Google" is ticked; the server validates.
(function () {
"use strict";
var $ = function (id) { return document.getElementById(id); };
var out = $("m-out"), err = $("m-error");
function show(text, isError) {
(isError ? err : out).textContent = text;
if (isError) out.textContent = ""; else err.textContent = "";
}
function request(method, path, body) {
var opts = { method: method, headers: { "Content-Type": "application/json" } };
if (body) opts.body = JSON.stringify(body);
return fetch(path, opts).then(function (res) {
return res.text().then(function (text) {
if (!res.ok) {
var msg = "HTTP " + res.status;
try { var j = JSON.parse(text); msg = (j.error || "") + ": " + (j.message || msg); } catch (e) {}
throw new Error(msg);
}
return JSON.parse(text);
});
});
}
function body() {
var q = $("m-q").value, q2 = $("m-q2").value;
return {
query: q, input: q, address: q, place_id: q, origin: q, destination: q2, filter: q,
lines: q, region: q2, locations: q + (q2 ? "|" + q2 : ""),
referrers: q, ips: "", apis: q2,
lat: $("m-lat").value, lng: $("m-lng").value, radius: $("m-radius").value,
timestamp: String(Math.floor(Date.now() / 1000)),
confirm: $("m-confirm").checked ? "true" : "false"
};
}
function clean(b) {
var o = {};
Object.keys(b).forEach(function (k) { if (b[k] !== "") o[k] = b[k]; });
return o;
}
$("m-run").addEventListener("click", function () {
var api = $("m-api").value;
var path = "/google/maps/" + api;
request("POST", path, clean(body()))
.then(function (j) { show(JSON.stringify(j, null, 2), false); })
.catch(function (e) { show(e.message, true); });
});
$("m-calls").addEventListener("click", function () {
request("GET", "/google/maps/calls")
.then(function (j) { show(JSON.stringify(j, null, 2), false); })
.catch(function (e) { show(e.message, true); });
});
request("GET", "/google/maps/status").then(function (j) {
$("m-config").textContent = j.configured
? "Credential configured. Maps key: " + (j.maps_key_present ? j.maps_key : "none") + "."
: "No Google credential: calls answer 503 until one is configured.";
}).catch(function () { $("m-config").textContent = "Status unavailable."; });
})();