universal-geocoder
Version:
Universal geocoding abstraction server-side and client-side with multiple built-in providers
128 lines • 5.73 kB
JavaScript
;
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var cross_fetch_1 = __importDefault(require("cross-fetch"));
var error_1 = require("./error");
var utils_1 = require("./utils");
var defaultOptions = {
protocol: "http",
method: "GET",
};
/**
* Load data from external geocoding engines.
*/
var ExternalLoader = /** @class */ (function () {
function ExternalLoader(options) {
if (options === void 0) { options = defaultOptions; }
this.options = defaultOptions;
this.setOptions(options);
}
ExternalLoader.prototype.setOptions = function (options) {
this.options = __assign(__assign({}, defaultOptions), options);
};
ExternalLoader.prototype.getOptions = function () {
return this.options;
};
ExternalLoader.prototype.executeRequest = function (params, callback, externalLoaderHeaders, body, errorCallback) {
var _a = this.options, protocol = _a.protocol, host = _a.host, pathname = _a.pathname, method = _a.method;
if (!host) {
throw new Error("A host is required for the external loader.");
}
if (!pathname) {
throw new Error("A pathname is required for the external loader.");
}
var requestUrl = new URL(protocol + "://" + host + "/" + pathname);
var jsonpCallback = params.jsonpCallback, requestParams = __rest(params, ["jsonpCallback"]);
var filteredRequestParams = utils_1.filterUndefinedObjectValues(requestParams);
Object.keys(filteredRequestParams).forEach(function (paramKey) {
var _a;
return requestUrl.searchParams.append(paramKey, (_a = filteredRequestParams[paramKey]) !== null && _a !== void 0 ? _a : "");
});
if (jsonpCallback) {
ExternalLoader.runJsonpCallback(requestUrl, callback, jsonpCallback);
return;
}
var headers = utils_1.filterUndefinedObjectValues(externalLoaderHeaders || {});
cross_fetch_1.default(requestUrl.toString(), {
headers: headers,
method: method,
body: method === "POST" ? JSON.stringify(body) : undefined,
})
.then(function (response) {
if (!response.ok) {
throw new error_1.ResponseError("Received HTTP status code " + response.status + " when attempting geocoding request.", response);
}
return response.json();
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.then(function (data) { return callback(data); })
.catch(function (error) {
if (errorCallback && error instanceof error_1.ResponseError) {
errorCallback(error);
return;
}
setTimeout(function () {
throw error;
});
});
};
ExternalLoader.runJsonpCallback = function (requestUrl, callback, jsonpCallback) {
if (!utils_1.isBrowser()) {
throw new Error('"jsonpCallback" parameter can only be used in a browser environment.');
}
requestUrl.searchParams.append(jsonpCallback, ExternalLoader.generateJsonpCallback(callback));
// Create a new script element.
var scriptElement = document.createElement("script");
// Set its source to the JSONP API.
scriptElement.src = requestUrl.toString();
// Stick the script element in the page <head>.
document.getElementsByTagName("head")[0].appendChild(scriptElement);
};
/**
* Generates randomly-named function to use as a callback for JSONP requests.
* @see https://github.com/OscarGodson/JSONP
*/
ExternalLoader.generateJsonpCallback = function (callback) {
// Use timestamp + a random factor to account for a lot of requests in a short time.
// e.g. jsonp1394571775161.
var timestamp = Date.now();
var generatedFunction = "jsonp" + Math.round(timestamp + Math.random() * 1000001);
// Generate the temp JSONP function using the name above.
// First, call the function the user defined in the callback param [callback(json)].
// Then delete the generated function from the window [delete window[generatedFunction]].
// eslint-disable-next-line @typescript-eslint/no-explicit-any
window[generatedFunction] = function (json) {
callback(json);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
delete window[generatedFunction];
};
return generatedFunction;
};
return ExternalLoader;
}());
exports.default = ExternalLoader;
//# sourceMappingURL=ExternalLoader.js.map