ItemFileReadStore.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945
  1. define("dojo/data/ItemFileReadStore", ["../_base/kernel", "../_base/lang", "../_base/declare", "../_base/array", "../_base/xhr",
  2. "../Evented", "../_base/window", "./util/filter", "./util/simpleFetch", "../date/stamp"
  3. ], function(kernel, lang, declare, array, xhr, Evented, window, filterUtil, simpleFetch, dateStamp) {
  4. // module:
  5. // dojo/data/ItemFileReadStore
  6. // summary:
  7. // TODOC
  8. var ItemFileReadStore = declare("dojo.data.ItemFileReadStore", [Evented],{
  9. // summary:
  10. // The ItemFileReadStore implements the dojo.data.api.Read API and reads
  11. // data from JSON files that have contents in this format --
  12. // { items: [
  13. // { name:'Kermit', color:'green', age:12, friends:['Gonzo', {_reference:{name:'Fozzie Bear'}}]},
  14. // { name:'Fozzie Bear', wears:['hat', 'tie']},
  15. // { name:'Miss Piggy', pets:'Foo-Foo'}
  16. // ]}
  17. // Note that it can also contain an 'identifer' property that specified which attribute on the items
  18. // in the array of items that acts as the unique identifier for that item.
  19. //
  20. constructor: function(/* Object */ keywordParameters){
  21. // summary: constructor
  22. // keywordParameters: {url: String}
  23. // keywordParameters: {data: jsonObject}
  24. // keywordParameters: {typeMap: object)
  25. // The structure of the typeMap object is as follows:
  26. // {
  27. // type0: function || object,
  28. // type1: function || object,
  29. // ...
  30. // typeN: function || object
  31. // }
  32. // Where if it is a function, it is assumed to be an object constructor that takes the
  33. // value of _value as the initialization parameters. If it is an object, then it is assumed
  34. // to be an object of general form:
  35. // {
  36. // type: function, //constructor.
  37. // deserialize: function(value) //The function that parses the value and constructs the object defined by type appropriately.
  38. // }
  39. this._arrayOfAllItems = [];
  40. this._arrayOfTopLevelItems = [];
  41. this._loadFinished = false;
  42. this._jsonFileUrl = keywordParameters.url;
  43. this._ccUrl = keywordParameters.url;
  44. this.url = keywordParameters.url;
  45. this._jsonData = keywordParameters.data;
  46. this.data = null;
  47. this._datatypeMap = keywordParameters.typeMap || {};
  48. if(!this._datatypeMap['Date']){
  49. //If no default mapping for dates, then set this as default.
  50. //We use the dojo.date.stamp here because the ISO format is the 'dojo way'
  51. //of generically representing dates.
  52. this._datatypeMap['Date'] = {
  53. type: Date,
  54. deserialize: function(value){
  55. return dateStamp.fromISOString(value);
  56. }
  57. };
  58. }
  59. this._features = {'dojo.data.api.Read':true, 'dojo.data.api.Identity':true};
  60. this._itemsByIdentity = null;
  61. this._storeRefPropName = "_S"; // Default name for the store reference to attach to every item.
  62. this._itemNumPropName = "_0"; // Default Item Id for isItem to attach to every item.
  63. this._rootItemPropName = "_RI"; // Default Item Id for isItem to attach to every item.
  64. this._reverseRefMap = "_RRM"; // Default attribute for constructing a reverse reference map for use with reference integrity
  65. this._loadInProgress = false; //Got to track the initial load to prevent duelling loads of the dataset.
  66. this._queuedFetches = [];
  67. if(keywordParameters.urlPreventCache !== undefined){
  68. this.urlPreventCache = keywordParameters.urlPreventCache?true:false;
  69. }
  70. if(keywordParameters.hierarchical !== undefined){
  71. this.hierarchical = keywordParameters.hierarchical?true:false;
  72. }
  73. if(keywordParameters.clearOnClose){
  74. this.clearOnClose = true;
  75. }
  76. if("failOk" in keywordParameters){
  77. this.failOk = keywordParameters.failOk?true:false;
  78. }
  79. },
  80. url: "", // use "" rather than undefined for the benefit of the parser (#3539)
  81. //Internal var, crossCheckUrl. Used so that setting either url or _jsonFileUrl, can still trigger a reload
  82. //when clearOnClose and close is used.
  83. _ccUrl: "",
  84. data: null, // define this so that the parser can populate it
  85. typeMap: null, //Define so parser can populate.
  86. //Parameter to allow users to specify if a close call should force a reload or not.
  87. //By default, it retains the old behavior of not clearing if close is called. But
  88. //if set true, the store will be reset to default state. Note that by doing this,
  89. //all item handles will become invalid and a new fetch must be issued.
  90. clearOnClose: false,
  91. //Parameter to allow specifying if preventCache should be passed to the xhrGet call or not when loading data from a url.
  92. //Note this does not mean the store calls the server on each fetch, only that the data load has preventCache set as an option.
  93. //Added for tracker: #6072
  94. urlPreventCache: false,
  95. //Parameter for specifying that it is OK for the xhrGet call to fail silently.
  96. failOk: false,
  97. //Parameter to indicate to process data from the url as hierarchical
  98. //(data items can contain other data items in js form). Default is true
  99. //for backwards compatibility. False means only root items are processed
  100. //as items, all child objects outside of type-mapped objects and those in
  101. //specific reference format, are left straight JS data objects.
  102. hierarchical: true,
  103. _assertIsItem: function(/* item */ item){
  104. // summary:
  105. // This function tests whether the item passed in is indeed an item in the store.
  106. // item:
  107. // The item to test for being contained by the store.
  108. if(!this.isItem(item)){
  109. throw new Error("dojo.data.ItemFileReadStore: Invalid item argument.");
  110. }
  111. },
  112. _assertIsAttribute: function(/* attribute-name-string */ attribute){
  113. // summary:
  114. // This function tests whether the item passed in is indeed a valid 'attribute' like type for the store.
  115. // attribute:
  116. // The attribute to test for being contained by the store.
  117. if(typeof attribute !== "string"){
  118. throw new Error("dojo.data.ItemFileReadStore: Invalid attribute argument.");
  119. }
  120. },
  121. getValue: function( /* item */ item,
  122. /* attribute-name-string */ attribute,
  123. /* value? */ defaultValue){
  124. // summary:
  125. // See dojo.data.api.Read.getValue()
  126. var values = this.getValues(item, attribute);
  127. return (values.length > 0)?values[0]:defaultValue; // mixed
  128. },
  129. getValues: function(/* item */ item,
  130. /* attribute-name-string */ attribute){
  131. // summary:
  132. // See dojo.data.api.Read.getValues()
  133. this._assertIsItem(item);
  134. this._assertIsAttribute(attribute);
  135. // Clone it before returning. refs: #10474
  136. return (item[attribute] || []).slice(0); // Array
  137. },
  138. getAttributes: function(/* item */ item){
  139. // summary:
  140. // See dojo.data.api.Read.getAttributes()
  141. this._assertIsItem(item);
  142. var attributes = [];
  143. for(var key in item){
  144. // Save off only the real item attributes, not the special id marks for O(1) isItem.
  145. if((key !== this._storeRefPropName) && (key !== this._itemNumPropName) && (key !== this._rootItemPropName) && (key !== this._reverseRefMap)){
  146. attributes.push(key);
  147. }
  148. }
  149. return attributes; // Array
  150. },
  151. hasAttribute: function( /* item */ item,
  152. /* attribute-name-string */ attribute){
  153. // summary:
  154. // See dojo.data.api.Read.hasAttribute()
  155. this._assertIsItem(item);
  156. this._assertIsAttribute(attribute);
  157. return (attribute in item);
  158. },
  159. containsValue: function(/* item */ item,
  160. /* attribute-name-string */ attribute,
  161. /* anything */ value){
  162. // summary:
  163. // See dojo.data.api.Read.containsValue()
  164. var regexp = undefined;
  165. if(typeof value === "string"){
  166. regexp = filterUtil.patternToRegExp(value, false);
  167. }
  168. return this._containsValue(item, attribute, value, regexp); //boolean.
  169. },
  170. _containsValue: function( /* item */ item,
  171. /* attribute-name-string */ attribute,
  172. /* anything */ value,
  173. /* RegExp?*/ regexp){
  174. // summary:
  175. // Internal function for looking at the values contained by the item.
  176. // description:
  177. // Internal function for looking at the values contained by the item. This
  178. // function allows for denoting if the comparison should be case sensitive for
  179. // strings or not (for handling filtering cases where string case should not matter)
  180. //
  181. // item:
  182. // The data item to examine for attribute values.
  183. // attribute:
  184. // The attribute to inspect.
  185. // value:
  186. // The value to match.
  187. // regexp:
  188. // Optional regular expression generated off value if value was of string type to handle wildcarding.
  189. // If present and attribute values are string, then it can be used for comparison instead of 'value'
  190. return array.some(this.getValues(item, attribute), function(possibleValue){
  191. if(possibleValue !== null && !lang.isObject(possibleValue) && regexp){
  192. if(possibleValue.toString().match(regexp)){
  193. return true; // Boolean
  194. }
  195. }else if(value === possibleValue){
  196. return true; // Boolean
  197. }
  198. });
  199. },
  200. isItem: function(/* anything */ something){
  201. // summary:
  202. // See dojo.data.api.Read.isItem()
  203. if(something && something[this._storeRefPropName] === this){
  204. if(this._arrayOfAllItems[something[this._itemNumPropName]] === something){
  205. return true;
  206. }
  207. }
  208. return false; // Boolean
  209. },
  210. isItemLoaded: function(/* anything */ something){
  211. // summary:
  212. // See dojo.data.api.Read.isItemLoaded()
  213. return this.isItem(something); //boolean
  214. },
  215. loadItem: function(/* object */ keywordArgs){
  216. // summary:
  217. // See dojo.data.api.Read.loadItem()
  218. this._assertIsItem(keywordArgs.item);
  219. },
  220. getFeatures: function(){
  221. // summary:
  222. // See dojo.data.api.Read.getFeatures()
  223. return this._features; //Object
  224. },
  225. getLabel: function(/* item */ item){
  226. // summary:
  227. // See dojo.data.api.Read.getLabel()
  228. if(this._labelAttr && this.isItem(item)){
  229. return this.getValue(item,this._labelAttr); //String
  230. }
  231. return undefined; //undefined
  232. },
  233. getLabelAttributes: function(/* item */ item){
  234. // summary:
  235. // See dojo.data.api.Read.getLabelAttributes()
  236. if(this._labelAttr){
  237. return [this._labelAttr]; //array
  238. }
  239. return null; //null
  240. },
  241. _fetchItems: function( /* Object */ keywordArgs,
  242. /* Function */ findCallback,
  243. /* Function */ errorCallback){
  244. // summary:
  245. // See dojo.data.util.simpleFetch.fetch()
  246. var self = this,
  247. filter = function(requestArgs, arrayOfItems){
  248. var items = [],
  249. i, key;
  250. if(requestArgs.query){
  251. var value,
  252. ignoreCase = requestArgs.queryOptions ? requestArgs.queryOptions.ignoreCase : false;
  253. //See if there are any string values that can be regexp parsed first to avoid multiple regexp gens on the
  254. //same value for each item examined. Much more efficient.
  255. var regexpList = {};
  256. for(key in requestArgs.query){
  257. value = requestArgs.query[key];
  258. if(typeof value === "string"){
  259. regexpList[key] = filterUtil.patternToRegExp(value, ignoreCase);
  260. }else if(value instanceof RegExp){
  261. regexpList[key] = value;
  262. }
  263. }
  264. for(i = 0; i < arrayOfItems.length; ++i){
  265. var match = true;
  266. var candidateItem = arrayOfItems[i];
  267. if(candidateItem === null){
  268. match = false;
  269. }else{
  270. for(key in requestArgs.query){
  271. value = requestArgs.query[key];
  272. if(!self._containsValue(candidateItem, key, value, regexpList[key])){
  273. match = false;
  274. }
  275. }
  276. }
  277. if(match){
  278. items.push(candidateItem);
  279. }
  280. }
  281. findCallback(items, requestArgs);
  282. }else{
  283. // We want a copy to pass back in case the parent wishes to sort the array.
  284. // We shouldn't allow resort of the internal list, so that multiple callers
  285. // can get lists and sort without affecting each other. We also need to
  286. // filter out any null values that have been left as a result of deleteItem()
  287. // calls in ItemFileWriteStore.
  288. for(i = 0; i < arrayOfItems.length; ++i){
  289. var item = arrayOfItems[i];
  290. if(item !== null){
  291. items.push(item);
  292. }
  293. }
  294. findCallback(items, requestArgs);
  295. }
  296. };
  297. if(this._loadFinished){
  298. filter(keywordArgs, this._getItemsArray(keywordArgs.queryOptions));
  299. }else{
  300. //Do a check on the JsonFileUrl and crosscheck it.
  301. //If it doesn't match the cross-check, it needs to be updated
  302. //This allows for either url or _jsonFileUrl to he changed to
  303. //reset the store load location. Done this way for backwards
  304. //compatibility. People use _jsonFileUrl (even though officially
  305. //private.
  306. if(this._jsonFileUrl !== this._ccUrl){
  307. kernel.deprecated("dojo.data.ItemFileReadStore: ",
  308. "To change the url, set the url property of the store," +
  309. " not _jsonFileUrl. _jsonFileUrl support will be removed in 2.0");
  310. this._ccUrl = this._jsonFileUrl;
  311. this.url = this._jsonFileUrl;
  312. }else if(this.url !== this._ccUrl){
  313. this._jsonFileUrl = this.url;
  314. this._ccUrl = this.url;
  315. }
  316. //See if there was any forced reset of data.
  317. if(this.data != null){
  318. this._jsonData = this.data;
  319. this.data = null;
  320. }
  321. if(this._jsonFileUrl){
  322. //If fetches come in before the loading has finished, but while
  323. //a load is in progress, we have to defer the fetching to be
  324. //invoked in the callback.
  325. if(this._loadInProgress){
  326. this._queuedFetches.push({args: keywordArgs, filter: filter});
  327. }else{
  328. this._loadInProgress = true;
  329. var getArgs = {
  330. url: self._jsonFileUrl,
  331. handleAs: "json-comment-optional",
  332. preventCache: this.urlPreventCache,
  333. failOk: this.failOk
  334. };
  335. var getHandler = xhr.get(getArgs);
  336. getHandler.addCallback(function(data){
  337. try{
  338. self._getItemsFromLoadedData(data);
  339. self._loadFinished = true;
  340. self._loadInProgress = false;
  341. filter(keywordArgs, self._getItemsArray(keywordArgs.queryOptions));
  342. self._handleQueuedFetches();
  343. }catch(e){
  344. self._loadFinished = true;
  345. self._loadInProgress = false;
  346. errorCallback(e, keywordArgs);
  347. }
  348. });
  349. getHandler.addErrback(function(error){
  350. self._loadInProgress = false;
  351. errorCallback(error, keywordArgs);
  352. });
  353. //Wire up the cancel to abort of the request
  354. //This call cancel on the deferred if it hasn't been called
  355. //yet and then will chain to the simple abort of the
  356. //simpleFetch keywordArgs
  357. var oldAbort = null;
  358. if(keywordArgs.abort){
  359. oldAbort = keywordArgs.abort;
  360. }
  361. keywordArgs.abort = function(){
  362. var df = getHandler;
  363. if(df && df.fired === -1){
  364. df.cancel();
  365. df = null;
  366. }
  367. if(oldAbort){
  368. oldAbort.call(keywordArgs);
  369. }
  370. };
  371. }
  372. }else if(this._jsonData){
  373. try{
  374. this._loadFinished = true;
  375. this._getItemsFromLoadedData(this._jsonData);
  376. this._jsonData = null;
  377. filter(keywordArgs, this._getItemsArray(keywordArgs.queryOptions));
  378. }catch(e){
  379. errorCallback(e, keywordArgs);
  380. }
  381. }else{
  382. errorCallback(new Error("dojo.data.ItemFileReadStore: No JSON source data was provided as either URL or a nested Javascript object."), keywordArgs);
  383. }
  384. }
  385. },
  386. _handleQueuedFetches: function(){
  387. // summary:
  388. // Internal function to execute delayed request in the store.
  389. //Execute any deferred fetches now.
  390. if(this._queuedFetches.length > 0){
  391. for(var i = 0; i < this._queuedFetches.length; i++){
  392. var fData = this._queuedFetches[i],
  393. delayedQuery = fData.args,
  394. delayedFilter = fData.filter;
  395. if(delayedFilter){
  396. delayedFilter(delayedQuery, this._getItemsArray(delayedQuery.queryOptions));
  397. }else{
  398. this.fetchItemByIdentity(delayedQuery);
  399. }
  400. }
  401. this._queuedFetches = [];
  402. }
  403. },
  404. _getItemsArray: function(/*object?*/queryOptions){
  405. // summary:
  406. // Internal function to determine which list of items to search over.
  407. // queryOptions: The query options parameter, if any.
  408. if(queryOptions && queryOptions.deep){
  409. return this._arrayOfAllItems;
  410. }
  411. return this._arrayOfTopLevelItems;
  412. },
  413. close: function(/*dojo.data.api.Request || keywordArgs || null */ request){
  414. // summary:
  415. // See dojo.data.api.Read.close()
  416. if(this.clearOnClose &&
  417. this._loadFinished &&
  418. !this._loadInProgress){
  419. //Reset all internalsback to default state. This will force a reload
  420. //on next fetch. This also checks that the data or url param was set
  421. //so that the store knows it can get data. Without one of those being set,
  422. //the next fetch will trigger an error.
  423. if(((this._jsonFileUrl == "" || this._jsonFileUrl == null) &&
  424. (this.url == "" || this.url == null)
  425. ) && this.data == null){
  426. console.debug("dojo.data.ItemFileReadStore: WARNING! Data reload " +
  427. " information has not been provided." +
  428. " Please set 'url' or 'data' to the appropriate value before" +
  429. " the next fetch");
  430. }
  431. this._arrayOfAllItems = [];
  432. this._arrayOfTopLevelItems = [];
  433. this._loadFinished = false;
  434. this._itemsByIdentity = null;
  435. this._loadInProgress = false;
  436. this._queuedFetches = [];
  437. }
  438. },
  439. _getItemsFromLoadedData: function(/* Object */ dataObject){
  440. // summary:
  441. // Function to parse the loaded data into item format and build the internal items array.
  442. // description:
  443. // Function to parse the loaded data into item format and build the internal items array.
  444. //
  445. // dataObject:
  446. // The JS data object containing the raw data to convery into item format.
  447. //
  448. // returns: array
  449. // Array of items in store item format.
  450. // First, we define a couple little utility functions...
  451. var addingArrays = false,
  452. self = this;
  453. function valueIsAnItem(/* anything */ aValue){
  454. // summary:
  455. // Given any sort of value that could be in the raw json data,
  456. // return true if we should interpret the value as being an
  457. // item itself, rather than a literal value or a reference.
  458. // example:
  459. // | false == valueIsAnItem("Kermit");
  460. // | false == valueIsAnItem(42);
  461. // | false == valueIsAnItem(new Date());
  462. // | false == valueIsAnItem({_type:'Date', _value:'1802-05-14'});
  463. // | false == valueIsAnItem({_reference:'Kermit'});
  464. // | true == valueIsAnItem({name:'Kermit', color:'green'});
  465. // | true == valueIsAnItem({iggy:'pop'});
  466. // | true == valueIsAnItem({foo:42});
  467. return (aValue !== null) &&
  468. (typeof aValue === "object") &&
  469. (!lang.isArray(aValue) || addingArrays) &&
  470. (!lang.isFunction(aValue)) &&
  471. (aValue.constructor == Object || lang.isArray(aValue)) &&
  472. (typeof aValue._reference === "undefined") &&
  473. (typeof aValue._type === "undefined") &&
  474. (typeof aValue._value === "undefined") &&
  475. self.hierarchical;
  476. }
  477. function addItemAndSubItemsToArrayOfAllItems(/* Item */ anItem){
  478. self._arrayOfAllItems.push(anItem);
  479. for(var attribute in anItem){
  480. var valueForAttribute = anItem[attribute];
  481. if(valueForAttribute){
  482. if(lang.isArray(valueForAttribute)){
  483. var valueArray = valueForAttribute;
  484. for(var k = 0; k < valueArray.length; ++k){
  485. var singleValue = valueArray[k];
  486. if(valueIsAnItem(singleValue)){
  487. addItemAndSubItemsToArrayOfAllItems(singleValue);
  488. }
  489. }
  490. }else{
  491. if(valueIsAnItem(valueForAttribute)){
  492. addItemAndSubItemsToArrayOfAllItems(valueForAttribute);
  493. }
  494. }
  495. }
  496. }
  497. }
  498. this._labelAttr = dataObject.label;
  499. // We need to do some transformations to convert the data structure
  500. // that we read from the file into a format that will be convenient
  501. // to work with in memory.
  502. // Step 1: Walk through the object hierarchy and build a list of all items
  503. var i,
  504. item;
  505. this._arrayOfAllItems = [];
  506. this._arrayOfTopLevelItems = dataObject.items;
  507. for(i = 0; i < this._arrayOfTopLevelItems.length; ++i){
  508. item = this._arrayOfTopLevelItems[i];
  509. if(lang.isArray(item)){
  510. addingArrays = true;
  511. }
  512. addItemAndSubItemsToArrayOfAllItems(item);
  513. item[this._rootItemPropName]=true;
  514. }
  515. // Step 2: Walk through all the attribute values of all the items,
  516. // and replace single values with arrays. For example, we change this:
  517. // { name:'Miss Piggy', pets:'Foo-Foo'}
  518. // into this:
  519. // { name:['Miss Piggy'], pets:['Foo-Foo']}
  520. //
  521. // We also store the attribute names so we can validate our store
  522. // reference and item id special properties for the O(1) isItem
  523. var allAttributeNames = {},
  524. key;
  525. for(i = 0; i < this._arrayOfAllItems.length; ++i){
  526. item = this._arrayOfAllItems[i];
  527. for(key in item){
  528. if(key !== this._rootItemPropName){
  529. var value = item[key];
  530. if(value !== null){
  531. if(!lang.isArray(value)){
  532. item[key] = [value];
  533. }
  534. }else{
  535. item[key] = [null];
  536. }
  537. }
  538. allAttributeNames[key]=key;
  539. }
  540. }
  541. // Step 3: Build unique property names to use for the _storeRefPropName and _itemNumPropName
  542. // This should go really fast, it will generally never even run the loop.
  543. while(allAttributeNames[this._storeRefPropName]){
  544. this._storeRefPropName += "_";
  545. }
  546. while(allAttributeNames[this._itemNumPropName]){
  547. this._itemNumPropName += "_";
  548. }
  549. while(allAttributeNames[this._reverseRefMap]){
  550. this._reverseRefMap += "_";
  551. }
  552. // Step 4: Some data files specify an optional 'identifier', which is
  553. // the name of an attribute that holds the identity of each item.
  554. // If this data file specified an identifier attribute, then build a
  555. // hash table of items keyed by the identity of the items.
  556. var arrayOfValues;
  557. var identifier = dataObject.identifier;
  558. if(identifier){
  559. this._itemsByIdentity = {};
  560. this._features['dojo.data.api.Identity'] = identifier;
  561. for(i = 0; i < this._arrayOfAllItems.length; ++i){
  562. item = this._arrayOfAllItems[i];
  563. arrayOfValues = item[identifier];
  564. var identity = arrayOfValues[0];
  565. if(!Object.hasOwnProperty.call(this._itemsByIdentity, identity)){
  566. this._itemsByIdentity[identity] = item;
  567. }else{
  568. if(this._jsonFileUrl){
  569. throw new Error("dojo.data.ItemFileReadStore: The json data as specified by: [" + this._jsonFileUrl + "] is malformed. Items within the list have identifier: [" + identifier + "]. Value collided: [" + identity + "]");
  570. }else if(this._jsonData){
  571. throw new Error("dojo.data.ItemFileReadStore: The json data provided by the creation arguments is malformed. Items within the list have identifier: [" + identifier + "]. Value collided: [" + identity + "]");
  572. }
  573. }
  574. }
  575. }else{
  576. this._features['dojo.data.api.Identity'] = Number;
  577. }
  578. // Step 5: Walk through all the items, and set each item's properties
  579. // for _storeRefPropName and _itemNumPropName, so that store.isItem() will return true.
  580. for(i = 0; i < this._arrayOfAllItems.length; ++i){
  581. item = this._arrayOfAllItems[i];
  582. item[this._storeRefPropName] = this;
  583. item[this._itemNumPropName] = i;
  584. }
  585. // Step 6: We walk through all the attribute values of all the items,
  586. // looking for type/value literals and item-references.
  587. //
  588. // We replace item-references with pointers to items. For example, we change:
  589. // { name:['Kermit'], friends:[{_reference:{name:'Miss Piggy'}}] }
  590. // into this:
  591. // { name:['Kermit'], friends:[miss_piggy] }
  592. // (where miss_piggy is the object representing the 'Miss Piggy' item).
  593. //
  594. // We replace type/value pairs with typed-literals. For example, we change:
  595. // { name:['Nelson Mandela'], born:[{_type:'Date', _value:'1918-07-18'}] }
  596. // into this:
  597. // { name:['Kermit'], born:(new Date(1918, 6, 18)) }
  598. //
  599. // We also generate the associate map for all items for the O(1) isItem function.
  600. for(i = 0; i < this._arrayOfAllItems.length; ++i){
  601. item = this._arrayOfAllItems[i]; // example: { name:['Kermit'], friends:[{_reference:{name:'Miss Piggy'}}] }
  602. for(key in item){
  603. arrayOfValues = item[key]; // example: [{_reference:{name:'Miss Piggy'}}]
  604. for(var j = 0; j < arrayOfValues.length; ++j){
  605. value = arrayOfValues[j]; // example: {_reference:{name:'Miss Piggy'}}
  606. if(value !== null && typeof value == "object"){
  607. if(("_type" in value) && ("_value" in value)){
  608. var type = value._type; // examples: 'Date', 'Color', or 'ComplexNumber'
  609. var mappingObj = this._datatypeMap[type]; // examples: Date, dojo.Color, foo.math.ComplexNumber, {type: dojo.Color, deserialize(value){ return new dojo.Color(value)}}
  610. if(!mappingObj){
  611. throw new Error("dojo.data.ItemFileReadStore: in the typeMap constructor arg, no object class was specified for the datatype '" + type + "'");
  612. }else if(lang.isFunction(mappingObj)){
  613. arrayOfValues[j] = new mappingObj(value._value);
  614. }else if(lang.isFunction(mappingObj.deserialize)){
  615. arrayOfValues[j] = mappingObj.deserialize(value._value);
  616. }else{
  617. throw new Error("dojo.data.ItemFileReadStore: Value provided in typeMap was neither a constructor, nor a an object with a deserialize function");
  618. }
  619. }
  620. if(value._reference){
  621. var referenceDescription = value._reference; // example: {name:'Miss Piggy'}
  622. if(!lang.isObject(referenceDescription)){
  623. // example: 'Miss Piggy'
  624. // from an item like: { name:['Kermit'], friends:[{_reference:'Miss Piggy'}]}
  625. arrayOfValues[j] = this._getItemByIdentity(referenceDescription);
  626. }else{
  627. // example: {name:'Miss Piggy'}
  628. // from an item like: { name:['Kermit'], friends:[{_reference:{name:'Miss Piggy'}}] }
  629. for(var k = 0; k < this._arrayOfAllItems.length; ++k){
  630. var candidateItem = this._arrayOfAllItems[k],
  631. found = true;
  632. for(var refKey in referenceDescription){
  633. if(candidateItem[refKey] != referenceDescription[refKey]){
  634. found = false;
  635. }
  636. }
  637. if(found){
  638. arrayOfValues[j] = candidateItem;
  639. }
  640. }
  641. }
  642. if(this.referenceIntegrity){
  643. var refItem = arrayOfValues[j];
  644. if(this.isItem(refItem)){
  645. this._addReferenceToMap(refItem, item, key);
  646. }
  647. }
  648. }else if(this.isItem(value)){
  649. //It's a child item (not one referenced through _reference).
  650. //We need to treat this as a referenced item, so it can be cleaned up
  651. //in a write store easily.
  652. if(this.referenceIntegrity){
  653. this._addReferenceToMap(value, item, key);
  654. }
  655. }
  656. }
  657. }
  658. }
  659. }
  660. },
  661. _addReferenceToMap: function(/*item*/ refItem, /*item*/ parentItem, /*string*/ attribute){
  662. // summary:
  663. // Method to add an reference map entry for an item and attribute.
  664. // description:
  665. // Method to add an reference map entry for an item and attribute. //
  666. // refItem:
  667. // The item that is referenced.
  668. // parentItem:
  669. // The item that holds the new reference to refItem.
  670. // attribute:
  671. // The attribute on parentItem that contains the new reference.
  672. //Stub function, does nothing. Real processing is in ItemFileWriteStore.
  673. },
  674. getIdentity: function(/* item */ item){
  675. // summary:
  676. // See dojo.data.api.Identity.getIdentity()
  677. var identifier = this._features['dojo.data.api.Identity'];
  678. if(identifier === Number){
  679. return item[this._itemNumPropName]; // Number
  680. }else{
  681. var arrayOfValues = item[identifier];
  682. if(arrayOfValues){
  683. return arrayOfValues[0]; // Object || String
  684. }
  685. }
  686. return null; // null
  687. },
  688. fetchItemByIdentity: function(/* Object */ keywordArgs){
  689. // summary:
  690. // See dojo.data.api.Identity.fetchItemByIdentity()
  691. // Hasn't loaded yet, we have to trigger the load.
  692. var item,
  693. scope;
  694. if(!this._loadFinished){
  695. var self = this;
  696. //Do a check on the JsonFileUrl and crosscheck it.
  697. //If it doesn't match the cross-check, it needs to be updated
  698. //This allows for either url or _jsonFileUrl to he changed to
  699. //reset the store load location. Done this way for backwards
  700. //compatibility. People use _jsonFileUrl (even though officially
  701. //private.
  702. if(this._jsonFileUrl !== this._ccUrl){
  703. kernel.deprecated("dojo.data.ItemFileReadStore: ",
  704. "To change the url, set the url property of the store," +
  705. " not _jsonFileUrl. _jsonFileUrl support will be removed in 2.0");
  706. this._ccUrl = this._jsonFileUrl;
  707. this.url = this._jsonFileUrl;
  708. }else if(this.url !== this._ccUrl){
  709. this._jsonFileUrl = this.url;
  710. this._ccUrl = this.url;
  711. }
  712. //See if there was any forced reset of data.
  713. if(this.data != null && this._jsonData == null){
  714. this._jsonData = this.data;
  715. this.data = null;
  716. }
  717. if(this._jsonFileUrl){
  718. if(this._loadInProgress){
  719. this._queuedFetches.push({args: keywordArgs});
  720. }else{
  721. this._loadInProgress = true;
  722. var getArgs = {
  723. url: self._jsonFileUrl,
  724. handleAs: "json-comment-optional",
  725. preventCache: this.urlPreventCache,
  726. failOk: this.failOk
  727. };
  728. var getHandler = xhr.get(getArgs);
  729. getHandler.addCallback(function(data){
  730. var scope = keywordArgs.scope?keywordArgs.scope:window.global;
  731. try{
  732. self._getItemsFromLoadedData(data);
  733. self._loadFinished = true;
  734. self._loadInProgress = false;
  735. item = self._getItemByIdentity(keywordArgs.identity);
  736. if(keywordArgs.onItem){
  737. keywordArgs.onItem.call(scope, item);
  738. }
  739. self._handleQueuedFetches();
  740. }catch(error){
  741. self._loadInProgress = false;
  742. if(keywordArgs.onError){
  743. keywordArgs.onError.call(scope, error);
  744. }
  745. }
  746. });
  747. getHandler.addErrback(function(error){
  748. self._loadInProgress = false;
  749. if(keywordArgs.onError){
  750. var scope = keywordArgs.scope?keywordArgs.scope:window.global;
  751. keywordArgs.onError.call(scope, error);
  752. }
  753. });
  754. }
  755. }else if(this._jsonData){
  756. // Passed in data, no need to xhr.
  757. self._getItemsFromLoadedData(self._jsonData);
  758. self._jsonData = null;
  759. self._loadFinished = true;
  760. item = self._getItemByIdentity(keywordArgs.identity);
  761. if(keywordArgs.onItem){
  762. scope = keywordArgs.scope?keywordArgs.scope:window.global;
  763. keywordArgs.onItem.call(scope, item);
  764. }
  765. }
  766. }else{
  767. // Already loaded. We can just look it up and call back.
  768. item = this._getItemByIdentity(keywordArgs.identity);
  769. if(keywordArgs.onItem){
  770. scope = keywordArgs.scope?keywordArgs.scope:window.global;
  771. keywordArgs.onItem.call(scope, item);
  772. }
  773. }
  774. },
  775. _getItemByIdentity: function(/* Object */ identity){
  776. // summary:
  777. // Internal function to look an item up by its identity map.
  778. var item = null;
  779. if(this._itemsByIdentity){
  780. // If this map is defined, we need to just try to get it. If it fails
  781. // the item does not exist.
  782. if(Object.hasOwnProperty.call(this._itemsByIdentity, identity)){
  783. item = this._itemsByIdentity[identity];
  784. }
  785. }else if (Object.hasOwnProperty.call(this._arrayOfAllItems, identity)){
  786. item = this._arrayOfAllItems[identity];
  787. }
  788. if(item === undefined){
  789. item = null;
  790. }
  791. return item; // Object
  792. },
  793. getIdentityAttributes: function(/* item */ item){
  794. // summary:
  795. // See dojo.data.api.Identity.getIdentityAttributes()
  796. var identifier = this._features['dojo.data.api.Identity'];
  797. if(identifier === Number){
  798. // If (identifier === Number) it means getIdentity() just returns
  799. // an integer item-number for each item. The dojo.data.api.Identity
  800. // spec says we need to return null if the identity is not composed
  801. // of attributes
  802. return null; // null
  803. }else{
  804. return [identifier]; // Array
  805. }
  806. },
  807. _forceLoad: function(){
  808. // summary:
  809. // Internal function to force a load of the store if it hasn't occurred yet. This is required
  810. // for specific functions to work properly.
  811. var self = this;
  812. //Do a check on the JsonFileUrl and crosscheck it.
  813. //If it doesn't match the cross-check, it needs to be updated
  814. //This allows for either url or _jsonFileUrl to he changed to
  815. //reset the store load location. Done this way for backwards
  816. //compatibility. People use _jsonFileUrl (even though officially
  817. //private.
  818. if(this._jsonFileUrl !== this._ccUrl){
  819. kernel.deprecated("dojo.data.ItemFileReadStore: ",
  820. "To change the url, set the url property of the store," +
  821. " not _jsonFileUrl. _jsonFileUrl support will be removed in 2.0");
  822. this._ccUrl = this._jsonFileUrl;
  823. this.url = this._jsonFileUrl;
  824. }else if(this.url !== this._ccUrl){
  825. this._jsonFileUrl = this.url;
  826. this._ccUrl = this.url;
  827. }
  828. //See if there was any forced reset of data.
  829. if(this.data != null){
  830. this._jsonData = this.data;
  831. this.data = null;
  832. }
  833. if(this._jsonFileUrl){
  834. var getArgs = {
  835. url: this._jsonFileUrl,
  836. handleAs: "json-comment-optional",
  837. preventCache: this.urlPreventCache,
  838. failOk: this.failOk,
  839. sync: true
  840. };
  841. var getHandler = xhr.get(getArgs);
  842. getHandler.addCallback(function(data){
  843. try{
  844. //Check to be sure there wasn't another load going on concurrently
  845. //So we don't clobber data that comes in on it. If there is a load going on
  846. //then do not save this data. It will potentially clobber current data.
  847. //We mainly wanted to sync/wait here.
  848. //TODO: Revisit the loading scheme of this store to improve multi-initial
  849. //request handling.
  850. if(self._loadInProgress !== true && !self._loadFinished){
  851. self._getItemsFromLoadedData(data);
  852. self._loadFinished = true;
  853. }else if(self._loadInProgress){
  854. //Okay, we hit an error state we can't recover from. A forced load occurred
  855. //while an async load was occurring. Since we cannot block at this point, the best
  856. //that can be managed is to throw an error.
  857. throw new Error("dojo.data.ItemFileReadStore: Unable to perform a synchronous load, an async load is in progress.");
  858. }
  859. }catch(e){
  860. console.log(e);
  861. throw e;
  862. }
  863. });
  864. getHandler.addErrback(function(error){
  865. throw error;
  866. });
  867. }else if(this._jsonData){
  868. self._getItemsFromLoadedData(self._jsonData);
  869. self._jsonData = null;
  870. self._loadFinished = true;
  871. }
  872. }
  873. });
  874. //Mix in the simple fetch implementation to this class.
  875. lang.extend(ItemFileReadStore,simpleFetch);
  876. return ItemFileReadStore;
  877. });