attribute.js

  1. 'use strict';
  2. // TODO consider refactoring this file so that the geoApi object is passed in along with the
  3. // esriBundle, then reference the shared module from it. See layer.js as example.
  4. const shared = require('./shared.js');
  5. /*
  6. Structure and naming:
  7. this is the Bundle. it is the topmost object in the structure.
  8. it packages up attributes for an entire layer object (i.e. FeatureLayer, DynamicLayer)
  9. {
  10. layerId: <layerId for layer>,
  11. indexes: ["6", "7"],
  12. "6": {
  13. <instance of a layer package, see below>
  14. },
  15. "7": {
  16. <instance of a layer package, see below>
  17. }
  18. }
  19. this is a layer Package. it contains information about a single server-side layer.
  20. note this is not always 1-to-1 with client side. a client side DynamicLayer can have
  21. many server-side sublayers, each with their own attribute sets
  22. DO NOT access the ._attribData property directly, as it will not exist until the first
  23. request for attributes. use the function .getAttribs(), as it will properly handle the
  24. initial request, or return the previously loaded result (always as a promise)
  25. {
  26. "layerId": "<layerid>",
  27. "featureIdx": 3,
  28. "getAttribs": getAttribs(),
  29. "_attribData": Promise(
  30. <instance of a attribute data object, see below>
  31. ),
  32. "layerData": Promise(
  33. <instance of a layer data object, see below>
  34. )
  35. }
  36. this is an attribute data object. it resides in a promise (as the data needs to be downloaded)
  37. it contains the attribute data as an array, and an index mapping object id to array position
  38. {
  39. "features": [
  40. {
  41. "attributes": {
  42. "objectid": 23,
  43. "name": "Bruce",
  44. "age": 27
  45. }
  46. },
  47. ...
  48. ],
  49. "oidIndex": {
  50. "23": 0,
  51. ...
  52. }
  53. }
  54. this is a layer data object. it contains information describing the server-side layer
  55. {
  56. "fields: [
  57. {
  58. "name": "objectid",
  59. "type": "esriFieldTypeOID",
  60. "alias": "OBJECTID"
  61. },
  62. ...
  63. ],
  64. "oidField": "objectid",
  65. "renderer": {...},
  66. "geometryType": "esriGeometryPoint",
  67. "minScale": 0,
  68. "maxScale": 0
  69. }
  70. */
  71. /**
  72. * Will generate an empty object structure to store a bundle of attributes for a full layer
  73. * @private
  74. * @return {Object} empty layer bundle object
  75. */
  76. function newLayerBundle(layerId) {
  77. const bundle = {
  78. layerId, // for easy access to know what layer the results belong to
  79. indexes: [], // for easy iteration over all indexes in the set
  80. registerData
  81. };
  82. function registerData(layerPackage) {
  83. layerPackage.layerId = bundle.layerId; // layerPackage is unaware of layerId. assign it during registration
  84. bundle[layerPackage.featureIdx.toString()] = layerPackage;
  85. bundle.indexes.push(layerPackage.featureIdx.toString());
  86. }
  87. return bundle;
  88. }
  89. /**
  90. * Will generate an empty object structure to store attributes for a single layer of features
  91. * @private
  92. * @param {Integer} featureIdx server index of the layer
  93. * @param {Object} esriBundle bundle of API classes
  94. * @return {Object} empty layer package object
  95. */
  96. function newLayerPackage(featureIdx, esriBundle) {
  97. // only reason this is in a function is to tack on the lazy-load
  98. // attribute function. all object properties are added elsewhere
  99. const layerPackage = {
  100. featureIdx,
  101. getAttribs
  102. };
  103. /**
  104. * Return promise of attribute data object. First request triggers load
  105. * @private
  106. * @return {Promise} promise of attribute data object
  107. */
  108. function getAttribs() {
  109. if (layerPackage._attribData) {
  110. // attributes have already been downloaded.
  111. return layerPackage._attribData;
  112. }
  113. // first request for data. create the promise
  114. layerPackage._attribData = new Promise((resolve, reject) => {
  115. // first wait for the layer specific data to finish loading
  116. // NOTE: by the time the application has access to getAttribs(), the .layerData
  117. // property will have been created.
  118. layerPackage.layerData.then(layerData => {
  119. // FIXME switch to native Promise
  120. const defFinished = new esriBundle.Deferred();
  121. const params = {
  122. maxId: -1,
  123. batchSize: -1,
  124. layerUrl: layerData.load.layerUrl,
  125. oidField: layerData.oidField,
  126. attribs: layerData.load.attribs,
  127. supportsLimit: layerData.load.supportsLimit,
  128. esriBundle
  129. };
  130. // begin the loading process
  131. loadDataBatch(params, defFinished);
  132. // after all data has been loaded
  133. defFinished.promise.then(features => {
  134. delete layerData.load; // no longer need this info
  135. // resolve the promise with the attribute set
  136. resolve(createAttribSet(layerData.oidField, features));
  137. }, error => {
  138. console.warn('error getting attribute data for ' + layerData.load.layerUrl);
  139. // attrib data deleted so the first check for attribData doesn't return a rejected promise
  140. delete layerPackage._attribData;
  141. reject(error);
  142. });
  143. });
  144. });
  145. return layerPackage._attribData;
  146. }
  147. return layerPackage;
  148. }
  149. /**
  150. * Will generate attribute package with object id indexes
  151. * @private
  152. * @param {String} oidField field containing object id
  153. * @param {Array} featureData feature objects to index and return
  154. * @return {Object} object containing features and an index by object id
  155. */
  156. function createAttribSet(oidField, featureData) {
  157. // add new data to layer data's array
  158. const res = {
  159. features: featureData,
  160. oidIndex: {}
  161. };
  162. // make index on object id
  163. featureData.forEach((elem, idx) => {
  164. // map object id to index of object in feature array
  165. // use toString, as objectid is integer and will act funny using array notation.
  166. res.oidIndex[elem.attributes[oidField].toString()] = idx;
  167. });
  168. return res;
  169. }
  170. // skim the last number off the Url
  171. // TODO apply more edge case tests to this function
  172. function getLayerIndex(layerUrl) {
  173. const re = /\/(\d+)\/?$/;
  174. const matches = layerUrl.match(re);
  175. if (matches) {
  176. return parseInt(matches[1]);
  177. }
  178. throw new Error('Cannot extract layer index from url ' + layerUrl);
  179. }
  180. /**
  181. * Recursive function to load a full set of attributes, regardless of the maximum output size of the service.
  182. * Passes result back on the provided Deferred object.
  183. *
  184. * @private
  185. * @param {Object} opts options object that consists of these properties
  186. * - maxId: integer, largest object id that has already been downloaded.
  187. * - supportsLimit: boolean, indicates if server result will notify us if our request surpassed the record limit.
  188. * - batchSize: integer, maximum number of results the service will return. if -1, means currently unknown. only required if supportsLimit is false.
  189. * - layerUrl: string, URL to feature layer endpoint.
  190. * - oidField: string, name of attribute containing the object id for the layer.
  191. * - attribs: string, a comma separated list of attributes to download. '*' will download all.
  192. * - esriBundle: object, standard set of ESRI API objects.
  193. * @param {Object} callerDef deferred object that resolves when current data has been downloaded
  194. */
  195. function loadDataBatch(opts, callerDef) {
  196. // fetch attributes from feature layer. where specifies records with id's higher than stuff already
  197. // downloaded. no geometry.
  198. // FIXME replace esriRequest with a library that handles proxies better
  199. const defData = opts.esriBundle.esriRequest({
  200. url: opts.layerUrl + '/query',
  201. content: {
  202. where: opts.oidField + '>' + opts.maxId,
  203. outFields: opts.attribs,
  204. returnGeometry: 'false',
  205. f: 'json',
  206. },
  207. callbackParamName: 'callback',
  208. handleAs: 'json'
  209. });
  210. defData.then(dataResult => {
  211. if (dataResult.features) {
  212. const len = dataResult.features.length;
  213. if (len > 0) {
  214. // figure out if we hit the end of the data. different logic for newer vs older servers.
  215. let moreData;
  216. if (opts.supportsLimit) {
  217. moreData = dataResult.exceededTransferLimit;
  218. } else {
  219. if (opts.batchSize === -1) {
  220. // this is our first batch. set the max batch size to this batch size
  221. opts.batchSize = len;
  222. }
  223. moreData = (len >= opts.batchSize);
  224. }
  225. if (moreData) {
  226. // stash the result and call the service again for the next batch of data.
  227. // max id becomes last object id in the current batch
  228. const thisDef = new opts.esriBundle.Deferred();
  229. opts.maxId = dataResult.features[len - 1].attributes[opts.oidField];
  230. loadDataBatch(opts, thisDef);
  231. thisDef.then(dataArray => {
  232. // chain the next result to our current result, then pass back to caller
  233. callerDef.resolve(dataResult.features.concat(dataArray));
  234. },
  235. error => {
  236. callerDef.reject(error);
  237. });
  238. } else {
  239. // done thanks
  240. callerDef.resolve(dataResult.features);
  241. }
  242. } else {
  243. // no more data. we are done
  244. callerDef.resolve([]);
  245. }
  246. } else {
  247. // it is possible to have an error, but it comes back on the "success" channel.
  248. callerDef.reject(dataResult.error);
  249. }
  250. },
  251. error => {
  252. callerDef.reject(error);
  253. });
  254. }
  255. /**
  256. * fetch attributes from an ESRI ArcGIS Server Feature Layer Service endpoint
  257. * @param {String} layerUrl an arcgis feature layer service endpoint
  258. * @param {Integer} featureIdx index of where the endpoint is. used for legend output
  259. * @param {String} attribs a comma separated list of attributes to download. '*' will download all
  260. * @param {Object} esriBundle bundle of API classes
  261. * @return {Object} attributes in a packaged format for asynch access
  262. */
  263. function loadFeatureAttribs(layerUrl, featureIdx, attribs, esriBundle, geoApi) {
  264. const layerPackage = newLayerPackage(getLayerIndex(layerUrl), esriBundle);
  265. // get information about this layer, asynch
  266. layerPackage.layerData = new Promise((resolve, reject) => {
  267. const layerData = {};
  268. // extract info for this service
  269. const defService = esriBundle.esriRequest({
  270. url: layerUrl,
  271. content: { f: 'json' },
  272. callbackParamName: 'callback',
  273. handleAs: 'json',
  274. });
  275. defService.then(serviceResult => {
  276. if (serviceResult && (typeof serviceResult.error === 'undefined')) {
  277. // properties for all endpoints
  278. layerData.layerType = serviceResult.type;
  279. layerData.geometryType = serviceResult.geometryType;
  280. layerData.minScale = serviceResult.minScale;
  281. layerData.maxScale = serviceResult.maxScale;
  282. layerData.supportsFeatures = false; // saves us from having to keep comparing type to 'Feature Layer' on the client
  283. if (serviceResult.type === 'Feature Layer') {
  284. layerData.supportsFeatures = true;
  285. layerData.fields = serviceResult.fields;
  286. // find object id field
  287. // NOTE cannot use arrow functions here due to bug
  288. serviceResult.fields.every(function (elem) {
  289. if (elem.type === 'esriFieldTypeOID') {
  290. layerData.oidField = elem.name;
  291. return false; // break the loop
  292. }
  293. return true; // keep looping
  294. });
  295. // ensure our attribute list contains the object id
  296. if (attribs !== '*') {
  297. if (attribs.split(',').indexOf(layerData.oidField) === -1) {
  298. attribs += (',' + layerData.oidField);
  299. }
  300. }
  301. // add renderer and legend
  302. layerData.renderer = serviceResult.drawingInfo.renderer;
  303. layerData.legend = geoApi.symbology.rendererToLegend(layerData.renderer, featureIdx);
  304. geoApi.symbology.enhanceRenderer(layerData.renderer, layerData.legend);
  305. // temporarily store things for delayed attributes
  306. layerData.load = {
  307. // version number is only provided on 10.0 SP1 servers and up.
  308. // servers 10.1 and higher support the query limit flag
  309. supportsLimit: (serviceResult.currentVersion || 1) >= 10.1,
  310. layerUrl,
  311. attribs
  312. };
  313. }
  314. // return the layer data promise result
  315. resolve(layerData);
  316. } else {
  317. // case where error happened but service request was successful
  318. console.warn('Service metadata load error');
  319. if (serviceResult && serviceResult.error) {
  320. // reject with error
  321. reject(serviceResult.error);
  322. } else {
  323. reject(new Error('Unknown error loading service metadata'));
  324. }
  325. }
  326. }, error => {
  327. // failed to load service info. reject with error
  328. console.warn('Service metadata load error : ' + error);
  329. reject(error);
  330. });
  331. });
  332. return layerPackage;
  333. }
  334. // extract the options (including defaults) for a layer index
  335. function pluckOptions(featureIdx, options = {}) {
  336. // handle missing layer
  337. const opt = options[featureIdx] || {};
  338. return {
  339. skip: opt.skip || false,
  340. attribs: opt.attribs || '*'
  341. };
  342. }
  343. /**
  344. * Ochestrate the attribute extraction of a feature layer object.
  345. * @private
  346. * @param {Object} layer an ESRI API Feature layer object
  347. * @param {Object} options information on layer and attribute skipping
  348. * @param {Object} esriBundle bundle of API classes
  349. * @return {Object} attributes in layer bundle format (see newLayerBundle)
  350. */
  351. function processFeatureLayer(layer, options, esriBundle, geoApi) {
  352. // logic is in separate function to passify the cyclomatic complexity check.
  353. // TODO we may want to support the option of a layer that points to a server based JSON file containing attributes
  354. const result = newLayerBundle(layer.id);
  355. if (layer.url) {
  356. const idx = getLayerIndex(layer.url);
  357. const opts = pluckOptions(idx, options);
  358. // check for skip flag
  359. if (!opts.skip) {
  360. // call loadFeatureAttribs with options if present
  361. result.registerData(loadFeatureAttribs(layer.url, idx, opts.attribs, esriBundle, geoApi));
  362. }
  363. } else {
  364. // feature layer was loaded from a file.
  365. // this approach is inefficient (duplicates attributes in layer and in attribute store),
  366. // but provides a consistent approach to attributes regardless of where the layer came from
  367. const layerPackage = newLayerPackage(0, esriBundle); // files have no index (no server), so we use value 0
  368. // it's local, no need to lazy-load
  369. layerPackage._attribData = Promise.resolve(createAttribSet(layer.objectIdField, layer.graphics.map(elem => {
  370. return { attributes: elem.attributes };
  371. })));
  372. const renderer = layer.renderer.toJson();
  373. const legend = geoApi.symbology.rendererToLegend(renderer, 0);
  374. geoApi.symbology.enhanceRenderer(renderer, legend);
  375. // TODO revisit the geometry type. ideally, fix our GeoJSON to Feature to populate the property
  376. layerPackage.layerData = Promise.resolve({
  377. oidField: layer.objectIdField,
  378. fields: layer.fields,
  379. geometryType: layer.geometryType || JSON.parse(layer._json).layerDefinition.drawingInfo.geometryType,
  380. minScale: layer.minScale,
  381. maxScale: layer.maxScale,
  382. renderer,
  383. legend
  384. });
  385. result.registerData(layerPackage);
  386. }
  387. return result;
  388. }
  389. /**
  390. * Ochestrate the attribute extraction of a dynamic map service layer object.
  391. * @private
  392. * @param {Object} layer an ESRI API Dynamic Map Service layer object
  393. * @param {Object} options information on layer and attribute skipping
  394. * @param {Object} esriBundle bundle of API classes
  395. * @return {Object} attributes in layer bundle format (see newLayerBundle)
  396. */
  397. function processDynamicLayer(layer, options, esriBundle, geoApi) {
  398. // logic is in separate function to passify the cyclomatic complexity check.
  399. // TODO we may want to support the option of a layer that points to a server based JSON file containing attributes
  400. let idx = 0;
  401. let opts;
  402. const result = newLayerBundle(layer.id);
  403. const lInfo = layer.layerInfos;
  404. // for each layer leaf. we use a custom loop as we need to skip sections
  405. while (idx < lInfo.length) {
  406. opts = pluckOptions(idx, options);
  407. // check if leaf node or group node
  408. if (lInfo[idx].subLayerIds) {
  409. // group node
  410. if (opts.skip) {
  411. // skip past all child indexes (thus avoiding processing all children).
  412. // group indexes have property .subLayerIds that lists indexes of all immediate child layers
  413. // child layers can be group layers as well.
  414. // example: to skip Group A (index 0), we crawl to Leaf X (index 4), then add 1 to get to sibling layer Leaf W (index 5)
  415. // [0] Group A
  416. // [1] Leaf Z
  417. // [2] Group B
  418. // [3] Leaf Y
  419. // [4] Leaf X
  420. // [5] Leaf W
  421. let lastIdx = idx;
  422. while (lInfo[lastIdx].subLayerIds) {
  423. // find last child index of this group. the last child may be a group itself so we keep processing the while loop
  424. lastIdx = lInfo[lastIdx].subLayerIds[
  425. lInfo[lastIdx].subLayerIds.length - 1];
  426. }
  427. // lastIdx has made it to the very last child in the original group node.
  428. // advance by 1 to get the next sibling index to the group
  429. idx = lastIdx + 1;
  430. } else {
  431. // advance to the first child layer
  432. idx += 1;
  433. }
  434. } else {
  435. // leaf node
  436. if (!opts.skip) {
  437. // load the features, store promise in array
  438. result.registerData(loadFeatureAttribs(layer.url + '/' + idx.toString(), idx,
  439. opts.attribs, esriBundle, geoApi));
  440. }
  441. // advance the loop
  442. idx += 1;
  443. }
  444. }
  445. return result;
  446. }
  447. function loadLayerAttribsBuilder(esriBundle, geoApi) {
  448. /**
  449. * Fetch attributes from a server-based Layer
  450. * @param {Object} layer an ESRI API layer object
  451. * @param {Object} options settings to determine if sub layers or certain attributes should be skipped.
  452. * @return {Object} attributes bundle for given layer
  453. */
  454. return (layer, options) => {
  455. /*
  456. format of the options object
  457. all parts are optional. default values are skip: false and attribs: "*"
  458. {
  459. "<layerindex a>": {
  460. "skip": true
  461. },
  462. "<layerindex b>": {
  463. "skip": false,
  464. "attribs": "field3,field8,field11"
  465. },
  466. "<layerindex d>": {
  467. }
  468. }
  469. */
  470. const shr = shared(esriBundle);
  471. const lType = shr.getLayerType(layer);
  472. switch (lType) {
  473. case 'FeatureLayer':
  474. return processFeatureLayer(layer, options, esriBundle, geoApi);
  475. case 'ArcGISDynamicMapServiceLayer':
  476. return processDynamicLayer(layer, options, esriBundle, geoApi);
  477. // case 'WmsLayer':
  478. // case 'ArcGISTiledMapServiceLayer':
  479. default:
  480. throw new Error('no support for loading attributes from layer type ' + lType);
  481. }
  482. };
  483. }
  484. // Attribute Loader related functions
  485. // TODO consider re-writing all the asynch stuff with the ECMA-7 style of asynch keywords
  486. module.exports = (esriBundle, geoApi) => {
  487. return {
  488. loadLayerAttribs: loadLayerAttribsBuilder(esriBundle, geoApi),
  489. getLayerIndex
  490. };
  491. };