Roo/data/JsonReader.js
[roojs1] / Roo / data / JsonReader.js
1 /*
2  * Based on:
3  * Ext JS Library 1.1.1
4  * Copyright(c) 2006-2007, Ext JS, LLC.
5  *
6  * Originally Released Under LGPL - original licence link has changed is not relivant.
7  *
8  * Fork - LGPL
9  * <script type="text/javascript">
10  */
11
12 /**
13  * @class Roo.data.JsonReader
14  * @extends Roo.data.DataReader
15  * Data reader class to create an Array of Roo.data.Record objects from a JSON response
16  * based on mappings in a provided Roo.data.Record constructor.
17  * 
18  * The default behaviour of a store is to send ?_requestMeta=1, unless the class has recieved 'metaData' property
19  * in the reply previously. 
20  * 
21  * <p>
22  * Example code:
23  * <pre><code>
24 var RecordDef = Roo.data.Record.create([
25     {name: 'name', mapping: 'name'},     // "mapping" property not needed if it's the same as "name"
26     {name: 'occupation'}                 // This field will use "occupation" as the mapping.
27 ]);
28 var myReader = new Roo.data.JsonReader({
29     totalProperty: "results",    // The property which contains the total dataset size (optional)
30     root: "rows",                // The property which contains an Array of row objects
31     id: "id"                     // The property within each row object that provides an ID for the record (optional)
32 }, RecordDef);
33 </code></pre>
34  * <p>
35  * This would consume a JSON file like this:
36  * <pre><code>
37 { 'results': 2, 'rows': [
38     { 'id': 1, 'name': 'Bill', occupation: 'Gardener' },
39     { 'id': 2, 'name': 'Ben', occupation: 'Horticulturalist' } ]
40 }
41 </code></pre>
42  * @cfg {String} totalProperty Name of the property from which to retrieve the total number of records
43  * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
44  * paged from the remote server.
45  * @cfg {String} successProperty Name of the property from which to retrieve the success attribute used by forms.
46  * @cfg {String} root name of the property which contains the Array of row objects.
47  * @cfg {String} id Name of the property within a row object that contains a record identifier value.
48  * @constructor
49  * Create a new JsonReader
50  * @param {Object} meta Metadata configuration options
51  * @param {Object} recordType Either an Array of field definition objects,
52  * or an {@link Roo.data.Record} object created using {@link Roo.data.Record#create}.
53  */
54 Roo.data.JsonReader = function(meta, recordType){
55     
56     meta = meta || {};
57     // set some defaults:
58     Roo.applyIf(meta, {
59         totalProperty: 'total',
60         successProperty : 'success',
61         root : 'data',
62         id : 'id'
63     });
64     
65     Roo.data.JsonReader.superclass.constructor.call(this, meta, recordType||meta.fields);
66 };
67 Roo.extend(Roo.data.JsonReader, Roo.data.DataReader, {
68     
69     /**
70      * @prop {Boolean} metaFromRemote  - if the meta data was loaded from the remote source.
71      * Used by Store query builder to append _requestMeta to params.
72      * 
73      */
74     metaFromRemote : false,
75     /**
76      * This method is only used by a DataProxy which has retrieved data from a remote server.
77      * @param {Object} response The XHR object which contains the JSON data in its responseText.
78      * @return {Object} data A data block which is used by an Roo.data.Store object as
79      * a cache of Roo.data.Records.
80      */
81     read : function(response){
82         var json = response.responseText;
83        
84         var o = /* eval:var:o */ eval("("+json+")");
85         if(!o) {
86             throw {message: "JsonReader.read: Json object not found"};
87         }
88         
89         if(o.metaData){
90             
91             delete this.ef;
92             this.metaFromRemote = true;
93             this.meta = o.metaData;
94             this.recordType = Roo.data.Record.create(o.metaData.fields);
95             this.onMetaChange(this.meta, this.recordType, o);
96         }
97         return this.readRecords(o);
98     },
99
100     // private function a store will implement
101     onMetaChange : function(meta, recordType, o){
102
103     },
104
105     /**
106          * @ignore
107          */
108     simpleAccess: function(obj, subsc) {
109         return obj[subsc];
110     },
111
112         /**
113          * @ignore
114          */
115     getJsonAccessor: function(){
116         var re = /[\[\.]/;
117         return function(expr) {
118             try {
119                 return(re.test(expr))
120                     ? new Function("obj", "return obj." + expr)
121                     : function(obj){
122                         return obj[expr];
123                     };
124             } catch(e){}
125             return Roo.emptyFn;
126         };
127     }(),
128
129     /**
130      * Create a data block containing Roo.data.Records from an XML document.
131      * @param {Object} o An object which contains an Array of row objects in the property specified
132      * in the config as 'root, and optionally a property, specified in the config as 'totalProperty'
133      * which contains the total size of the dataset.
134      * @return {Object} data A data block which is used by an Roo.data.Store object as
135      * a cache of Roo.data.Records.
136      */
137     readRecords : function(o){
138         /**
139          * After any data loads, the raw JSON data is available for further custom processing.
140          * @type Object
141          */
142         this.o = o;
143         var s = this.meta, Record = this.recordType,
144             f = Record ? Record.prototype.fields : null, fi = f.items, fl = f.length;
145
146 //      Generate extraction functions for the totalProperty, the root, the id, and for each field
147         if (!this.ef) {
148             if(s.totalProperty) {
149                     this.getTotal = this.getJsonAccessor(s.totalProperty);
150                 }
151                 if(s.successProperty) {
152                     this.getSuccess = this.getJsonAccessor(s.successProperty);
153                 }
154                 this.getRoot = s.root ? this.getJsonAccessor(s.root) : function(p){return p;};
155                 if (s.id) {
156                         var g = this.getJsonAccessor(s.id);
157                         this.getId = function(rec) {
158                                 var r = g(rec);  
159                                 return (r === undefined || r === "") ? null : r;
160                         };
161                 } else {
162                         this.getId = function(){return null;};
163                 }
164             this.ef = [];
165             for(var jj = 0; jj < fl; jj++){
166                 f = fi[jj];
167                 var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
168                 this.ef[jj] = this.getJsonAccessor(map);
169             }
170         }
171
172         var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
173         if(s.totalProperty){
174             var vt = parseInt(this.getTotal(o), 10);
175             if(!isNaN(vt)){
176                 totalRecords = vt;
177             }
178         }
179         if(s.successProperty){
180             var vs = this.getSuccess(o);
181             if(vs === false || vs === 'false'){
182                 success = false;
183             }
184         }
185         var records = [];
186         for(var i = 0; i < c; i++){
187                 var n = root[i];
188             var values = {};
189             var id = this.getId(n);
190             for(var j = 0; j < fl; j++){
191                 f = fi[j];
192             var v = this.ef[j](n);
193             if (!f.convert) {
194                 Roo.log('missing convert for ' + f.name);
195                 Roo.log(f);
196                 continue;
197             }
198             values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue);
199             }
200             var record = new Record(values, id);
201             record.json = n;
202             records[i] = record;
203         }
204         return {
205             raw : o,
206             success : success,
207             records : records,
208             totalRecords : totalRecords
209         };
210     }
211 });