ItemFileReadStore.js 33 KB

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