Created
August 16, 2017 00:05
-
-
Save andygup/0097db25cf65954846ab729351663cce to your computer and use it in GitHub Desktop.
Demographics analysis with self-renewing ArcGIS token
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| This ArcGIS-based pubnub block shows a pattern for running powerful demographic data searches. | |
| Declare the Event Handler with the export syntax. The incoming message is called request. | |
| The request object can either be a single point or a polygon. Here is an example, 'y' is Latitude | |
| and 'x' is Longitude: | |
| { | |
| "x": -122.435, | |
| "y": 37.785 | |
| } | |
| */ | |
| export default (request) => { | |
| // Require XHR to make external calls | |
| const xhr = require("xhr"); | |
| // Require console to print debug information | |
| const console = require('console'); | |
| // Need a token? Create a free developer account at developers.arcgis.com | |
| // Information on auto-majically generating a token: http://resources.arcgis.com/en/help/arcgis-rest-api/index.html#//02r3000000m5000000 | |
| const accessToken = "jmWtooJqFI8vLL8bxkwxJtM7BHnJT-r8pYHDXljhckAPyghQwayml9IOOpXnRXQ4C2mHGNUb98MdpraxjvgPHj1hnNuNRUjrF_6ndBxcw8aIx4h9YAd5rmgiYIhjbAKLu18xvoVT1V8cRG18butZRQ.."; | |
| const url = "https://www.arcgis.com/sharing/rest/oauth2/token/"; | |
| const CLIENT_ID = '<GET THIS FROM DEVELOPERS.ARCGIS.COM>'; | |
| const CLIENT_SECRET = '<GET THIS FROM DEVELOPERS.ARCGIS.COM>'; | |
| const http_options = { | |
| "method": "POST", | |
| "headers": { | |
| "Content-Type": "application/x-www-form-urlencoded" | |
| }, | |
| // For more info on variable names: http://doc.arcgis.com/en/esri-demographics/ | |
| "body":"&client_id=" + CLIENT_ID + | |
| "&grant_type=client_credentials"+ | |
| "&client_secret=" + CLIENT_SECRET | |
| }; | |
| return getToken().then(() => { | |
| const arcgisToken = request.message.arcgisToken; | |
| return getDemographics(arcgisToken); | |
| }) | |
| function getToken(){ | |
| const store = require('kvstore'); | |
| return store.getItem('arcgisToken').then((value) => { | |
| console.log(value); | |
| if (value !== "null") { | |
| request.message.arcgisToken = value; | |
| // console.log(`Token Exists: ${value}`); | |
| return request; | |
| } | |
| else { | |
| return xhr.fetch(url, http_options).then((x) => { | |
| const body = JSON.parse(x.body); | |
| console.log(body); | |
| store.setItem('arcgisToken', body.access_token, (body.expires_in / 60) - 5); | |
| request.message.arcgisToken = body.access_token; | |
| return request; | |
| }).catch((exc) => { | |
| console.log("Exception in xhr request: " + exc); | |
| return request.abort() | |
| }); | |
| } | |
| }) | |
| } | |
| function getDemographics(accessToken){ | |
| try { | |
| // NOTE: The manually created developer access token expires in 24 hours ;-) | |
| const http_options = { | |
| "method": "POST", | |
| "headers": { | |
| "Content-Type": "application/x-www-form-urlencoded" | |
| }, | |
| // For more info on variable names: http://doc.arcgis.com/en/esri-demographics/ | |
| "body":"f=json" + | |
| "&studyAreas=[{'geometry':{'x':" + request.message.lon + ",'y':" + request.message.lat + "}}]" + | |
| "&analysisvariables=['populationtotals.TOTPOP_CY','Wealth.MEDHINC_CY','5yearincrements.MEDAGE_CY']" + | |
| "&token=" + accessToken | |
| }; | |
| // ArcGIS REST API call | |
| // Documentation for the ArcGIS Geoenrichment service: https://developers.arcgis.com/rest/geoenrichment/api-reference/geoenrichment-service-overview.htm | |
| console.log("test", http_options); | |
| const url = "https://geoenrich.arcgis.com/arcgis/rest/services/World/geoenrichmentserver/GeoEnrichment/enrich"; | |
| return xhr.fetch(url, http_options).then((x) => { | |
| const body = JSON.parse(x.body); | |
| if(body.hasOwnProperty("error")){ | |
| if(body.error.hasOwnProperty("code") === 498){ | |
| console.log("TOKEN EXPIRED!"); | |
| return getToken().then(() => { | |
| const arcgisToken = request.message.arcgisToken; | |
| return getDemographics(arcgisToken); | |
| }); | |
| } | |
| } | |
| else { | |
| // Remove everything but attributes information to cleanup the console output | |
| // You can get a description of the attributes here: https://developers.arcgis.com/rest/geoenrichment/api-reference/get-variables.htm | |
| const totalPopulation = body.results[0].value.FeatureSet[0].features[0].attributes.TOTPOP_CY; | |
| const medianHouseholdIncome = body.results[0].value.FeatureSet[0].features[0].attributes.MEDHINC_CY; | |
| const medianAge = body.results[0].value.FeatureSet[0].features[0].attributes.MEDAGE_CY; | |
| console.log( | |
| "Total Population: " + totalPopulation + | |
| ", Median Household Income: " + medianHouseholdIncome + | |
| ", Median Age: " + medianAge | |
| ); | |
| request.message.data = { | |
| "totalPopulation":totalPopulation, | |
| "medianHouseholdIncome": medianHouseholdIncome, | |
| "medianAge": medianAge | |
| }; | |
| } | |
| return request.ok(); | |
| }).catch((x) => { | |
| console.log("Exception in xhr request: " + x); | |
| }); | |
| } catch (e) { | |
| console.error('Uncaught exception:', e); | |
| return request.abort(); | |
| } | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment