Upgrade to ExtJS 4.0.1 - Released 05/18/2011
[extjs.git] / src / data / reader / Reader.js
1 /**
2  * @author Ed Spencer
3  * @class Ext.data.reader.Reader
4  * @extends Object
5  * 
6  * <p>Readers are used to interpret data to be loaded into a {@link Ext.data.Model Model} instance or a {@link Ext.data.Store Store}
7  * - usually in response to an AJAX request. This is normally handled transparently by passing some configuration to either the 
8  * {@link Ext.data.Model Model} or the {@link Ext.data.Store Store} in question - see their documentation for further details.</p>
9  * 
10  * <p><u>Loading Nested Data</u></p>
11  * 
12  * <p>Readers have the ability to automatically load deeply-nested data objects based on the {@link Ext.data.Association associations}
13  * configured on each Model. Below is an example demonstrating the flexibility of these associations in a fictional CRM system which
14  * manages a User, their Orders, OrderItems and Products. First we'll define the models:
15  * 
16 <pre><code>
17 Ext.define("User", {
18     extend: 'Ext.data.Model',
19     fields: [
20         'id', 'name'
21     ],
22
23     hasMany: {model: 'Order', name: 'orders'},
24
25     proxy: {
26         type: 'rest',
27         url : 'users.json',
28         reader: {
29             type: 'json',
30             root: 'users'
31         }
32     }
33 });
34
35 Ext.define("Order", {
36     extend: 'Ext.data.Model',
37     fields: [
38         'id', 'total'
39     ],
40
41     hasMany  : {model: 'OrderItem', name: 'orderItems', associationKey: 'order_items'},
42     belongsTo: 'User'
43 });
44
45 Ext.define("OrderItem", {
46     extend: 'Ext.data.Model',
47     fields: [
48         'id', 'price', 'quantity', 'order_id', 'product_id'
49     ],
50
51     belongsTo: ['Order', {model: 'Product', associationKey: 'product'}]
52 });
53
54 Ext.define("Product", {
55     extend: 'Ext.data.Model',
56     fields: [
57         'id', 'name'
58     ],
59
60     hasMany: 'OrderItem'
61 });
62 </code></pre>
63  * 
64  * <p>This may be a lot to take in - basically a User has many Orders, each of which is composed of several OrderItems. Finally,
65  * each OrderItem has a single Product. This allows us to consume data like this:</p>
66  * 
67 <pre><code>
68 {
69     "users": [
70         {
71             "id": 123,
72             "name": "Ed",
73             "orders": [
74                 {
75                     "id": 50,
76                     "total": 100,
77                     "order_items": [
78                         {
79                             "id"      : 20,
80                             "price"   : 40,
81                             "quantity": 2,
82                             "product" : {
83                                 "id": 1000,
84                                 "name": "MacBook Pro"
85                             }
86                         },
87                         {
88                             "id"      : 21,
89                             "price"   : 20,
90                             "quantity": 3,
91                             "product" : {
92                                 "id": 1001,
93                                 "name": "iPhone"
94                             }
95                         }
96                     ]
97                 }
98             ]
99         }
100     ]
101 }
102 </code></pre>
103  * 
104  * <p>The JSON response is deeply nested - it returns all Users (in this case just 1 for simplicity's sake), all of the Orders
105  * for each User (again just 1 in this case), all of the OrderItems for each Order (2 order items in this case), and finally
106  * the Product associated with each OrderItem. Now we can read the data and use it as follows:
107  * 
108 <pre><code>
109 var store = new Ext.data.Store({
110     model: "User"
111 });
112
113 store.load({
114     callback: function() {
115         //the user that was loaded
116         var user = store.first();
117
118         console.log("Orders for " + user.get('name') + ":")
119
120         //iterate over the Orders for each User
121         user.orders().each(function(order) {
122             console.log("Order ID: " + order.getId() + ", which contains items:");
123
124             //iterate over the OrderItems for each Order
125             order.orderItems().each(function(orderItem) {
126                 //we know that the Product data is already loaded, so we can use the synchronous getProduct
127                 //usually, we would use the asynchronous version (see {@link Ext.data.BelongsToAssociation})
128                 var product = orderItem.getProduct();
129
130                 console.log(orderItem.get('quantity') + ' orders of ' + product.get('name'));
131             });
132         });
133     }
134 });
135 </code></pre>
136  * 
137  * <p>Running the code above results in the following:</p>
138  * 
139 <pre><code>
140 Orders for Ed:
141 Order ID: 50, which contains items:
142 2 orders of MacBook Pro
143 3 orders of iPhone
144 </code></pre>
145  * 
146  * @constructor
147  * @param {Object} config Optional config object
148  */
149 Ext.define('Ext.data.reader.Reader', {
150     requires: ['Ext.data.ResultSet'],
151     alternateClassName: ['Ext.data.Reader', 'Ext.data.DataReader'],
152     
153     /**
154      * @cfg {String} idProperty Name of the property within a row object
155      * that contains a record identifier value.  Defaults to <tt>The id of the model</tt>.
156      * If an idProperty is explicitly specified it will override that of the one specified
157      * on the model
158      */
159
160     /**
161      * @cfg {String} totalProperty Name of the property from which to
162      * retrieve the total number of records in the dataset. This is only needed
163      * if the whole dataset is not passed in one go, but is being paged from
164      * the remote server.  Defaults to <tt>total</tt>.
165      */
166     totalProperty: 'total',
167
168     /**
169      * @cfg {String} successProperty Name of the property from which to
170      * retrieve the success attribute. Defaults to <tt>success</tt>.  See
171      * {@link Ext.data.proxy.Proxy}.{@link Ext.data.proxy.Proxy#exception exception}
172      * for additional information.
173      */
174     successProperty: 'success',
175
176     /**
177      * @cfg {String} root <b>Required</b>.  The name of the property
178      * which contains the Array of row objects.  Defaults to <tt>undefined</tt>.
179      * An exception will be thrown if the root property is undefined. The data
180      * packet value for this property should be an empty array to clear the data
181      * or show no data.
182      */
183     root: '',
184     
185     /**
186      * @cfg {String} messageProperty The name of the property which contains a response message.
187      * This property is optional.
188      */
189     
190     /**
191      * @cfg {Boolean} implicitIncludes True to automatically parse models nested within other models in a response
192      * object. See the Ext.data.reader.Reader intro docs for full explanation. Defaults to true.
193      */
194     implicitIncludes: true,
195     
196     isReader: true,
197     
198     constructor: function(config) {
199         var me = this;
200         
201         Ext.apply(me, config || {});
202         me.fieldCount = 0;
203         me.model = Ext.ModelManager.getModel(config.model);
204         if (me.model) {
205             me.buildExtractors();
206         }
207     },
208
209     /**
210      * Sets a new model for the reader.
211      * @private
212      * @param {Object} model The model to set.
213      * @param {Boolean} setOnProxy True to also set on the Proxy, if one is configured
214      */
215     setModel: function(model, setOnProxy) {
216         var me = this;
217         
218         me.model = Ext.ModelManager.getModel(model);
219         me.buildExtractors(true);
220         
221         if (setOnProxy && me.proxy) {
222             me.proxy.setModel(me.model, true);
223         }
224     },
225
226     /**
227      * Reads the given response object. This method normalizes the different types of response object that may be passed
228      * to it, before handing off the reading of records to the {@link #readRecords} function.
229      * @param {Object} response The response object. This may be either an XMLHttpRequest object or a plain JS object
230      * @return {Ext.data.ResultSet} The parsed ResultSet object
231      */
232     read: function(response) {
233         var data = response;
234         
235         if (response && response.responseText) {
236             data = this.getResponseData(response);
237         }
238         
239         if (data) {
240             return this.readRecords(data);
241         } else {
242             return this.nullResultSet;
243         }
244     },
245
246     /**
247      * Abstracts common functionality used by all Reader subclasses. Each subclass is expected to call
248      * this function before running its own logic and returning the Ext.data.ResultSet instance. For most
249      * Readers additional processing should not be needed.
250      * @param {Mixed} data The raw data object
251      * @return {Ext.data.ResultSet} A ResultSet object
252      */
253     readRecords: function(data) {
254         var me  = this;
255         
256         /*
257          * We check here whether the number of fields has changed since the last read.
258          * This works around an issue when a Model is used for both a Tree and another
259          * source, because the tree decorates the model with extra fields and it causes
260          * issues because the readers aren't notified.
261          */
262         if (me.fieldCount !== me.getFields().length) {
263             me.buildExtractors(true);
264         }
265         
266         /**
267          * The raw data object that was last passed to readRecords. Stored for further processing if needed
268          * @property rawData
269          * @type Mixed
270          */
271         me.rawData = data;
272
273         data = me.getData(data);
274
275         // If we pass an array as the data, we dont use getRoot on the data.
276         // Instead the root equals to the data.
277         var root    = Ext.isArray(data) ? data : me.getRoot(data),
278             success = true,
279             recordCount = 0,
280             total, value, records, message;
281             
282         if (root) {
283             total = root.length;
284         }
285
286         if (me.totalProperty) {
287             value = parseInt(me.getTotal(data), 10);
288             if (!isNaN(value)) {
289                 total = value;
290             }
291         }
292
293         if (me.successProperty) {
294             value = me.getSuccess(data);
295             if (value === false || value === 'false') {
296                 success = false;
297             }
298         }
299         
300         if (me.messageProperty) {
301             message = me.getMessage(data);
302         }
303         
304         if (root) {
305             records = me.extractData(root);
306             recordCount = records.length;
307         } else {
308             recordCount = 0;
309             records = [];
310         }
311
312         return Ext.create('Ext.data.ResultSet', {
313             total  : total || recordCount,
314             count  : recordCount,
315             records: records,
316             success: success,
317             message: message
318         });
319     },
320
321     /**
322      * Returns extracted, type-cast rows of data.  Iterates to call #extractValues for each row
323      * @param {Object[]/Object} data-root from server response
324      * @private
325      */
326     extractData : function(root) {
327         var me = this,
328             values  = [],
329             records = [],
330             Model   = me.model,
331             i       = 0,
332             length  = root.length,
333             idProp  = me.getIdProperty(),
334             node, id, record;
335             
336         if (!root.length && Ext.isObject(root)) {
337             root = [root];
338             length = 1;
339         }
340
341         for (; i < length; i++) {
342             node   = root[i];
343             values = me.extractValues(node);
344             id     = me.getId(node);
345
346             
347             record = new Model(values, id, node);
348             records.push(record);
349                 
350             if (me.implicitIncludes) {
351                 me.readAssociated(record, node);
352             }
353         }
354
355         return records;
356     },
357     
358     /**
359      * @private
360      * Loads a record's associations from the data object. This prepopulates hasMany and belongsTo associations
361      * on the record provided.
362      * @param {Ext.data.Model} record The record to load associations for
363      * @param {Mixed} data The data object
364      * @return {String} Return value description
365      */
366     readAssociated: function(record, data) {
367         var associations = record.associations.items,
368             i            = 0,
369             length       = associations.length,
370             association, associationData, proxy, reader;
371         
372         for (; i < length; i++) {
373             association     = associations[i];
374             associationData = this.getAssociatedDataRoot(data, association.associationKey || association.name);
375             
376             if (associationData) {
377                 reader = association.getReader();
378                 if (!reader) {
379                     proxy = association.associatedModel.proxy;
380                     // if the associated model has a Reader already, use that, otherwise attempt to create a sensible one
381                     if (proxy) {
382                         reader = proxy.getReader();
383                     } else {
384                         reader = new this.constructor({
385                             model: association.associatedName
386                         });
387                     }
388                 }
389                 association.read(record, reader, associationData);
390             }  
391         }
392     },
393     
394     /**
395      * @private
396      * Used internally by {@link #readAssociated}. Given a data object (which could be json, xml etc) for a specific
397      * record, this should return the relevant part of that data for the given association name. This is only really
398      * needed to support the XML Reader, which has to do a query to get the associated data object
399      * @param {Mixed} data The raw data object
400      * @param {String} associationName The name of the association to get data for (uses associationKey if present)
401      * @return {Mixed} The root
402      */
403     getAssociatedDataRoot: function(data, associationName) {
404         return data[associationName];
405     },
406     
407     getFields: function() {
408         return this.model.prototype.fields.items;
409     },
410
411     /**
412      * @private
413      * Given an object representing a single model instance's data, iterates over the model's fields and
414      * builds an object with the value for each field.
415      * @param {Object} data The data object to convert
416      * @return {Object} Data object suitable for use with a model constructor
417      */
418     extractValues: function(data) {
419         var fields = this.getFields(),
420             i      = 0,
421             length = fields.length,
422             output = {},
423             field, value;
424
425         for (; i < length; i++) {
426             field = fields[i];
427             value = this.extractorFunctions[i](data);
428
429             output[field.name] = value;
430         }
431
432         return output;
433     },
434
435     /**
436      * @private
437      * By default this function just returns what is passed to it. It can be overridden in a subclass
438      * to return something else. See XmlReader for an example.
439      * @param {Object} data The data object
440      * @return {Object} The normalized data object
441      */
442     getData: function(data) {
443         return data;
444     },
445
446     /**
447      * @private
448      * This will usually need to be implemented in a subclass. Given a generic data object (the type depends on the type
449      * of data we are reading), this function should return the object as configured by the Reader's 'root' meta data config.
450      * See XmlReader's getRoot implementation for an example. By default the same data object will simply be returned.
451      * @param {Mixed} data The data object
452      * @return {Mixed} The same data object
453      */
454     getRoot: function(data) {
455         return data;
456     },
457
458     /**
459      * Takes a raw response object (as passed to this.read) and returns the useful data segment of it. This must be implemented by each subclass
460      * @param {Object} response The responce object
461      * @return {Object} The useful data from the response
462      */
463     getResponseData: function(response) {
464         //<debug>
465         Ext.Error.raise("getResponseData must be implemented in the Ext.data.reader.Reader subclass");
466         //</debug>
467     },
468
469     /**
470      * @private
471      * Reconfigures the meta data tied to this Reader
472      */
473     onMetaChange : function(meta) {
474         var fields = meta.fields,
475             newModel;
476         
477         Ext.apply(this, meta);
478         
479         if (fields) {
480             newModel = Ext.define("Ext.data.reader.Json-Model" + Ext.id(), {
481                 extend: 'Ext.data.Model',
482                 fields: fields
483             });
484             this.setModel(newModel, true);
485         } else {
486             this.buildExtractors(true);
487         }
488     },
489     
490     /**
491      * Get the idProperty to use for extracting data
492      * @private
493      * @return {String} The id property
494      */
495     getIdProperty: function(){
496         var prop = this.idProperty;
497         if (Ext.isEmpty(prop)) {
498             prop = this.model.prototype.idProperty;
499         }
500         return prop;
501     },
502
503     /**
504      * @private
505      * This builds optimized functions for retrieving record data and meta data from an object.
506      * Subclasses may need to implement their own getRoot function.
507      * @param {Boolean} force True to automatically remove existing extractor functions first (defaults to false)
508      */
509     buildExtractors: function(force) {
510         var me          = this,
511             idProp      = me.getIdProperty(),
512             totalProp   = me.totalProperty,
513             successProp = me.successProperty,
514             messageProp = me.messageProperty,
515             accessor;
516             
517         if (force === true) {
518             delete me.extractorFunctions;
519         }
520         
521         if (me.extractorFunctions) {
522             return;
523         }   
524
525         //build the extractors for all the meta data
526         if (totalProp) {
527             me.getTotal = me.createAccessor(totalProp);
528         }
529
530         if (successProp) {
531             me.getSuccess = me.createAccessor(successProp);
532         }
533
534         if (messageProp) {
535             me.getMessage = me.createAccessor(messageProp);
536         }
537
538         if (idProp) {
539             accessor = me.createAccessor(idProp);
540
541             me.getId = function(record) {
542                 var id = accessor.call(me, record);
543                 return (id === undefined || id === '') ? null : id;
544             };
545         } else {
546             me.getId = function() {
547                 return null;
548             };
549         }
550         me.buildFieldExtractors();
551     },
552
553     /**
554      * @private
555      */
556     buildFieldExtractors: function() {
557         //now build the extractors for all the fields
558         var me = this,
559             fields = me.getFields(),
560             ln = fields.length,
561             i  = 0,
562             extractorFunctions = [],
563             field, map;
564
565         for (; i < ln; i++) {
566             field = fields[i];
567             map   = (field.mapping !== undefined && field.mapping !== null) ? field.mapping : field.name;
568
569             extractorFunctions.push(me.createAccessor(map));
570         }
571         me.fieldCount = ln;
572
573         me.extractorFunctions = extractorFunctions;
574     }
575 }, function() {
576     Ext.apply(this, {
577         // Private. Empty ResultSet to return when response is falsy (null|undefined|empty string)
578         nullResultSet: Ext.create('Ext.data.ResultSet', {
579             total  : 0,
580             count  : 0,
581             records: [],
582             success: true
583         })
584     });
585 });