Skip to content

Instantly share code, notes, and snippets.

@raykendo
Created January 18, 2016 17:00
Show Gist options
  • Save raykendo/0755046c8003633d885f to your computer and use it in GitHub Desktop.
Save raykendo/0755046c8003633d885f to your computer and use it in GitHub Desktop.
Dojo plugin to parse URL parameters and translate them to a where clause for an ArcGIS JavaScript API Query
/**
* A dojo plugin that extracts possible query parameters from the URL.
* @module search/UrlSearch
*/
define(["esri/urlUtils"], function (urlUtils) {
// regex for parameter names to ignore
var ignoreParameters = [
/^appid$/i, // ArcGIS Online uses appid parameter to define application id
/^folderid$/i, // ArcGIS Online uses folderid to define folder hash where webmap is stored
/^webmap$/i // ArcGIS Online uses webmap property to define the map to use in the application
// TODO: add more default parameters to ignore from AGOL
],
/**
* An object to store and get search parameters from the URL
* @constructor
*/
ParsedUrl = function () {};
/**
* Overrides toString method to create a viable SQL Query string
* @function toString
* @returns {string} - string value for the search where query string.
*/
ParsedUrl.prototype.toString = function () {
var params = [], name, value;
for (name in this) {
if (this.hasOwnProperty(name)) {
value = this[name];
if (/^\d+$/.test(value)) {
params.push([name, value].join(" = "));
}
params.push([name, " LIKE '", value, "%'"].join(""));
}
}
if (params.length) {
return "(" + params.join(") OR (") + ")";
}
return "";
};
return {
load: function (id, require, callback) {
// parse either the value assigned through the id parameter, or the current URL
var urlObj = urlUtils.urlToObject(id || window.location.href),
cleanedObj = new ParsedUrl(), u;
// for each property in the URL query
for (u in urlObj.query) {
// if the url parameter is not in the list of parameter names to ignore..
if (!ignoreParameters.some(function (parameterName) {
return parameterName.test(u);
})) {
// add parameter and its value to the results
cleanedObj[u] = urlObj.query[u];
}
}
// send back the url query object with parameters not in the ignore list,
// and a way to parse the values into a SQL where string.
return callback(cleanedObj);
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment