Upgrade to ExtJS 3.1.1 - Released 02/08/2010
[extjs.git] / src / data / JsonReader.js
1 /*!
2  * Ext JS Library 3.1.1
3  * Copyright(c) 2006-2010 Ext JS, LLC
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**
8  * @class Ext.data.JsonReader
9  * @extends Ext.data.DataReader
10  * <p>Data reader class to create an Array of {@link Ext.data.Record} objects
11  * from a JSON packet based on mappings in a provided {@link Ext.data.Record}
12  * constructor.</p>
13  * <p>Example code:</p>
14  * <pre><code>
15 var myReader = new Ext.data.JsonReader({
16     // metadata configuration options:
17     {@link #idProperty}: 'id'
18     {@link #root}: 'rows',
19     {@link #totalProperty}: 'results',
20     {@link Ext.data.DataReader#messageProperty}: "msg"  // The element within the response that provides a user-feedback message (optional)
21
22     // the fields config option will internally create an {@link Ext.data.Record}
23     // constructor that provides mapping for reading the record data objects
24     {@link Ext.data.DataReader#fields fields}: [
25         // map Record&#39;s 'firstname' field to data object&#39;s key of same name
26         {name: 'name'},
27         // map Record&#39;s 'job' field to data object&#39;s 'occupation' key
28         {name: 'job', mapping: 'occupation'}
29     ]
30 });
31 </code></pre>
32  * <p>This would consume a JSON data object of the form:</p><pre><code>
33 {
34     results: 2000, // Reader&#39;s configured {@link #totalProperty}
35     rows: [        // Reader&#39;s configured {@link #root}
36         // record data objects:
37         { {@link #idProperty id}: 1, firstname: 'Bill', occupation: 'Gardener' },
38         { {@link #idProperty id}: 2, firstname: 'Ben' , occupation: 'Horticulturalist' },
39         ...
40     ]
41 }
42 </code></pre>
43  * <p><b><u>Automatic configuration using metaData</u></b></p>
44  * <p>It is possible to change a JsonReader's metadata at any time by including
45  * a <b><tt>metaData</tt></b> property in the JSON data object. If the JSON data
46  * object has a <b><tt>metaData</tt></b> property, a {@link Ext.data.Store Store}
47  * object using this Reader will reconfigure itself to use the newly provided
48  * field definition and fire its {@link Ext.data.Store#metachange metachange}
49  * event. The metachange event handler may interrogate the <b><tt>metaData</tt></b>
50  * property to perform any configuration required.</p>
51  * <p>Note that reconfiguring a Store potentially invalidates objects which may
52  * refer to Fields or Records which no longer exist.</p>
53  * <p>To use this facility you would create the JsonReader like this:</p><pre><code>
54 var myReader = new Ext.data.JsonReader();
55 </code></pre>
56  * <p>The first data packet from the server would configure the reader by
57  * containing a <b><tt>metaData</tt></b> property <b>and</b> the data. For
58  * example, the JSON data object might take the form:</p><pre><code>
59 {
60     metaData: {
61         "{@link #idProperty}": "id",
62         "{@link #root}": "rows",
63         "{@link #totalProperty}": "results"
64         "{@link #successProperty}": "success",
65         "{@link Ext.data.DataReader#fields fields}": [
66             {"name": "name"},
67             {"name": "job", "mapping": "occupation"}
68         ],
69         // used by store to set its sortInfo
70         "sortInfo":{
71            "field": "name",
72            "direction": "ASC"
73         },
74         // {@link Ext.PagingToolbar paging data} (if applicable)
75         "start": 0,
76         "limit": 2,
77         // custom property
78         "foo": "bar"
79     },
80     // Reader&#39;s configured {@link #successProperty}
81     "success": true,
82     // Reader&#39;s configured {@link #totalProperty}
83     "results": 2000,
84     // Reader&#39;s configured {@link #root}
85     // (this data simulates 2 results {@link Ext.PagingToolbar per page})
86     "rows": [ // <b>*Note:</b> this must be an Array
87         { "id": 1, "name": "Bill", "occupation": "Gardener" },
88         { "id": 2, "name":  "Ben", "occupation": "Horticulturalist" }
89     ]
90 }
91  * </code></pre>
92  * <p>The <b><tt>metaData</tt></b> property in the JSON data object should contain:</p>
93  * <div class="mdetail-params"><ul>
94  * <li>any of the configuration options for this class</li>
95  * <li>a <b><tt>{@link Ext.data.Record#fields fields}</tt></b> property which
96  * the JsonReader will use as an argument to the
97  * {@link Ext.data.Record#create data Record create method} in order to
98  * configure the layout of the Records it will produce.</li>
99  * <li>a <b><tt>{@link Ext.data.Store#sortInfo sortInfo}</tt></b> property
100  * which the JsonReader will use to set the {@link Ext.data.Store}'s
101  * {@link Ext.data.Store#sortInfo sortInfo} property</li>
102  * <li>any custom properties needed</li>
103  * </ul></div>
104  *
105  * @constructor
106  * Create a new JsonReader
107  * @param {Object} meta Metadata configuration options.
108  * @param {Array/Object} recordType
109  * <p>Either an Array of {@link Ext.data.Field Field} definition objects (which
110  * will be passed to {@link Ext.data.Record#create}, or a {@link Ext.data.Record Record}
111  * constructor created from {@link Ext.data.Record#create}.</p>
112  */
113 Ext.data.JsonReader = function(meta, recordType){
114     meta = meta || {};
115     /**
116      * @cfg {String} idProperty [id] Name of the property within a row object
117      * that contains a record identifier value.  Defaults to <tt>id</tt>
118      */
119     /**
120      * @cfg {String} successProperty [success] Name of the property from which to
121      * retrieve the success attribute. Defaults to <tt>success</tt>.  See
122      * {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#exception exception}
123      * for additional information.
124      */
125     /**
126      * @cfg {String} totalProperty [total] Name of the property from which to
127      * retrieve the total number of records in the dataset. This is only needed
128      * if the whole dataset is not passed in one go, but is being paged from
129      * the remote server.  Defaults to <tt>total</tt>.
130      */
131     /**
132      * @cfg {String} root [undefined] <b>Required</b>.  The name of the property
133      * which contains the Array of row objects.  Defaults to <tt>undefined</tt>.
134      * An exception will be thrown if the root property is undefined. The data
135      * packet value for this property should be an empty array to clear the data
136      * or show no data.
137      */
138     Ext.applyIf(meta, {
139         idProperty: 'id',
140         successProperty: 'success',
141         totalProperty: 'total'
142     });
143
144     Ext.data.JsonReader.superclass.constructor.call(this, meta, recordType || meta.fields);
145 };
146 Ext.extend(Ext.data.JsonReader, Ext.data.DataReader, {
147     /**
148      * This JsonReader's metadata as passed to the constructor, or as passed in
149      * the last data packet's <b><tt>metaData</tt></b> property.
150      * @type Mixed
151      * @property meta
152      */
153     /**
154      * This method is only used by a DataProxy which has retrieved data from a remote server.
155      * @param {Object} response The XHR object which contains the JSON data in its responseText.
156      * @return {Object} data A data block which is used by an Ext.data.Store object as
157      * a cache of Ext.data.Records.
158      */
159     read : function(response){
160         var json = response.responseText;
161         var o = Ext.decode(json);
162         if(!o) {
163             throw {message: 'JsonReader.read: Json object not found'};
164         }
165         return this.readRecords(o);
166     },
167
168     /**
169      * Decode a json response from server.
170      * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]
171      * @param {Object} response
172      * TODO: refactor code between JsonReader#readRecords, #readResponse into 1 method.
173      * there's ugly duplication going on due to maintaining backwards compat. with 2.0.  It's time to do this.
174      */
175     readResponse : function(action, response) {
176         var o = (response.responseText !== undefined) ? Ext.decode(response.responseText) : response;
177         if(!o) {
178             throw new Ext.data.JsonReader.Error('response');
179         }
180
181         var root = this.getRoot(o);
182         if (action === Ext.data.Api.actions.create) {
183             var def = Ext.isDefined(root);
184             if (def && Ext.isEmpty(root)) {
185                 throw new Ext.data.JsonReader.Error('root-empty', this.meta.root);
186             }
187             else if (!def) {
188                 throw new Ext.data.JsonReader.Error('root-undefined-response', this.meta.root);
189             }
190         }
191
192         // instantiate response object
193         var res = new Ext.data.Response({
194             action: action,
195             success: this.getSuccess(o),
196             data: (root) ? this.extractData(root, false) : [],
197             message: this.getMessage(o),
198             raw: o
199         });
200
201         // blow up if no successProperty
202         if (Ext.isEmpty(res.success)) {
203             throw new Ext.data.JsonReader.Error('successProperty-response', this.meta.successProperty);
204         }
205         return res;
206     },
207
208     /**
209      * Create a data block containing Ext.data.Records from a JSON object.
210      * @param {Object} o An object which contains an Array of row objects in the property specified
211      * in the config as 'root, and optionally a property, specified in the config as 'totalProperty'
212      * which contains the total size of the dataset.
213      * @return {Object} data A data block which is used by an Ext.data.Store object as
214      * a cache of Ext.data.Records.
215      */
216     readRecords : function(o){
217         /**
218          * After any data loads, the raw JSON data is available for further custom processing.  If no data is
219          * loaded or there is a load exception this property will be undefined.
220          * @type Object
221          */
222         this.jsonData = o;
223         if(o.metaData){
224             this.onMetaChange(o.metaData);
225         }
226         var s = this.meta, Record = this.recordType,
227             f = Record.prototype.fields, fi = f.items, fl = f.length, v;
228
229         var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
230         if(s.totalProperty){
231             v = parseInt(this.getTotal(o), 10);
232             if(!isNaN(v)){
233                 totalRecords = v;
234             }
235         }
236         if(s.successProperty){
237             v = this.getSuccess(o);
238             if(v === false || v === 'false'){
239                 success = false;
240             }
241         }
242
243         // TODO return Ext.data.Response instance instead.  @see #readResponse
244         return {
245             success : success,
246             records : this.extractData(root, true), // <-- true to return [Ext.data.Record]
247             totalRecords : totalRecords
248         };
249     },
250
251     // private
252     buildExtractors : function() {
253         if(this.ef){
254             return;
255         }
256         var s = this.meta, Record = this.recordType,
257             f = Record.prototype.fields, fi = f.items, fl = f.length;
258
259         if(s.totalProperty) {
260             this.getTotal = this.createAccessor(s.totalProperty);
261         }
262         if(s.successProperty) {
263             this.getSuccess = this.createAccessor(s.successProperty);
264         }
265         if (s.messageProperty) {
266             this.getMessage = this.createAccessor(s.messageProperty);
267         }
268         this.getRoot = s.root ? this.createAccessor(s.root) : function(p){return p;};
269         if (s.id || s.idProperty) {
270             var g = this.createAccessor(s.id || s.idProperty);
271             this.getId = function(rec) {
272                 var r = g(rec);
273                 return (r === undefined || r === '') ? null : r;
274             };
275         } else {
276             this.getId = function(){return null;};
277         }
278         var ef = [];
279         for(var i = 0; i < fl; i++){
280             f = fi[i];
281             var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
282             ef.push(this.createAccessor(map));
283         }
284         this.ef = ef;
285     },
286
287     /**
288      * @ignore
289      * TODO This isn't used anywhere??  Don't we want to use this where possible instead of complex #createAccessor?
290      */
291     simpleAccess : function(obj, subsc) {
292         return obj[subsc];
293     },
294
295     /**
296      * @ignore
297      */
298     createAccessor : function(){
299         var re = /[\[\.]/;
300         return function(expr) {
301             if(Ext.isEmpty(expr)){
302                 return Ext.emptyFn;
303             }
304             if(Ext.isFunction(expr)){
305                 return expr;
306             }
307             var i = String(expr).search(re);
308             if(i >= 0){
309                 return new Function('obj', 'return obj' + (i > 0 ? '.' : '') + expr);
310             }
311             return function(obj){
312                 return obj[expr];
313             };
314
315         };
316     }(),
317
318     /**
319      * type-casts a single row of raw-data from server
320      * @param {Object} data
321      * @param {Array} items
322      * @param {Integer} len
323      * @private
324      */
325     extractValues : function(data, items, len) {
326         var f, values = {};
327         for(var j = 0; j < len; j++){
328             f = items[j];
329             var v = this.ef[j](data);
330             values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue, data);
331         }
332         return values;
333     }
334 });
335
336 /**
337  * @class Ext.data.JsonReader.Error
338  * Error class for JsonReader
339  */
340 Ext.data.JsonReader.Error = Ext.extend(Ext.Error, {
341     constructor : function(message, arg) {
342         this.arg = arg;
343         Ext.Error.call(this, message);
344     },
345     name : 'Ext.data.JsonReader'
346 });
347 Ext.apply(Ext.data.JsonReader.Error.prototype, {
348     lang: {
349         'response': 'An error occurred while json-decoding your server response',
350         'successProperty-response': 'Could not locate your "successProperty" in your server response.  Please review your JsonReader config to ensure the config-property "successProperty" matches the property in your server-response.  See the JsonReader docs.',
351         'root-undefined-config': 'Your JsonReader was configured without a "root" property.  Please review your JsonReader config and make sure to define the root property.  See the JsonReader docs.',
352         'idProperty-undefined' : 'Your JsonReader was configured without an "idProperty"  Please review your JsonReader configuration and ensure the "idProperty" is set (e.g.: "id").  See the JsonReader docs.',
353         'root-empty': 'Data was expected to be returned by the server in the "root" property of the response.  Please review your JsonReader configuration to ensure the "root" property matches that returned in the server-response.  See JsonReader docs.'
354     }
355 });