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