Upgrade to ExtJS 3.3.1 - Released 11/30/2010
[extjs.git] / src / data / XmlReader.js
1 /*!
2  * Ext JS Library 3.3.1
3  * Copyright(c) 2006-2010 Sencha Inc.
4  * licensing@sencha.com
5  * http://www.sencha.com/license
6  */
7 /**
8  * @class Ext.data.XmlReader
9  * @extends Ext.data.DataReader
10  * <p>Data reader class to create an Array of {@link Ext.data.Record} objects from an XML document
11  * based on mappings in a provided {@link Ext.data.Record} constructor.</p>
12  * <p><b>Note</b>: that in order for the browser to parse a returned XML document, the Content-Type
13  * header in the HTTP response must be set to "text/xml" or "application/xml".</p>
14  * <p>Example code:</p>
15  * <pre><code>
16 var Employee = Ext.data.Record.create([
17    {name: 'name', mapping: 'name'},     // "mapping" property not needed if it is the same as "name"
18    {name: 'occupation'}                 // This field will use "occupation" as the mapping.
19 ]);
20 var myReader = new Ext.data.XmlReader({
21    totalProperty: "results", // The element which contains the total dataset size (optional)
22    record: "row",           // The repeated element which contains row information
23    idProperty: "id"         // The element within the row that provides an ID for the record (optional)
24    messageProperty: "msg"   // The element within the response that provides a user-feedback message (optional)
25 }, Employee);
26 </code></pre>
27  * <p>
28  * This would consume an XML file like this:
29  * <pre><code>
30 &lt;?xml version="1.0" encoding="UTF-8"?>
31 &lt;dataset>
32  &lt;results>2&lt;/results>
33  &lt;row>
34    &lt;id>1&lt;/id>
35    &lt;name>Bill&lt;/name>
36    &lt;occupation>Gardener&lt;/occupation>
37  &lt;/row>
38  &lt;row>
39    &lt;id>2&lt;/id>
40    &lt;name>Ben&lt;/name>
41    &lt;occupation>Horticulturalist&lt;/occupation>
42  &lt;/row>
43 &lt;/dataset>
44 </code></pre>
45  * @cfg {String} totalProperty The DomQuery path from which to retrieve the total number of records
46  * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
47  * paged from the remote server.
48  * @cfg {String} record The DomQuery path to the repeated element which contains record information.
49  * @cfg {String} record The DomQuery path to the repeated element which contains record information.
50  * @cfg {String} successProperty The DomQuery path to the success attribute used by forms.
51  * @cfg {String} idPath The DomQuery path relative from the record element to the element that contains
52  * a record identifier value.
53  * @constructor
54  * Create a new XmlReader.
55  * @param {Object} meta Metadata configuration options
56  * @param {Object} recordType Either an Array of field definition objects as passed to
57  * {@link Ext.data.Record#create}, or a Record constructor object created using {@link Ext.data.Record#create}.
58  */
59 Ext.data.XmlReader = function(meta, recordType){
60     meta = meta || {};
61
62     // backwards compat, convert idPath or id / success
63     Ext.applyIf(meta, {
64         idProperty: meta.idProperty || meta.idPath || meta.id,
65         successProperty: meta.successProperty || meta.success
66     });
67
68     Ext.data.XmlReader.superclass.constructor.call(this, meta, recordType || meta.fields);
69 };
70 Ext.extend(Ext.data.XmlReader, Ext.data.DataReader, {
71     /**
72      * This method is only used by a DataProxy which has retrieved data from a remote server.
73      * @param {Object} response The XHR object which contains the parsed XML document.  The response is expected
74      * to contain a property called <tt>responseXML</tt> which refers to an XML document object.
75      * @return {Object} records A data block which is used by an {@link Ext.data.Store} as
76      * a cache of Ext.data.Records.
77      */
78     read : function(response){
79         var doc = response.responseXML;
80         if(!doc) {
81             throw {message: "XmlReader.read: XML Document not available"};
82         }
83         return this.readRecords(doc);
84     },
85
86     /**
87      * Create a data block containing Ext.data.Records from an XML document.
88      * @param {Object} doc A parsed XML document.
89      * @return {Object} records A data block which is used by an {@link Ext.data.Store} as
90      * a cache of Ext.data.Records.
91      */
92     readRecords : function(doc){
93         /**
94          * After any data loads/reads, the raw XML Document is available for further custom processing.
95          * @type XMLDocument
96          */
97         this.xmlData = doc;
98
99         var root    = doc.documentElement || doc,
100             q       = Ext.DomQuery,
101             totalRecords = 0,
102             success = true;
103
104         if(this.meta.totalProperty){
105             totalRecords = this.getTotal(root, 0);
106         }
107         if(this.meta.successProperty){
108             success = this.getSuccess(root);
109         }
110
111         var records = this.extractData(q.select(this.meta.record, root), true); // <-- true to return Ext.data.Record[]
112
113         // TODO return Ext.data.Response instance.  @see #readResponse
114         return {
115             success : success,
116             records : records,
117             totalRecords : totalRecords || records.length
118         };
119     },
120
121     /**
122      * Decode an XML response from server.
123      * @param {String} action [{@link Ext.data.Api#actions} create|read|update|destroy]
124      * @param {Object} response HTTP Response object from browser.
125      * @return {Ext.data.Response} An instance of {@link Ext.data.Response}
126      */
127     readResponse : function(action, response) {
128         var q = Ext.DomQuery,
129             doc = response.responseXML,
130             root = doc.documentElement || doc;
131
132         // create general Response instance.
133         var res = new Ext.data.Response({
134             action: action,
135             success : this.getSuccess(root),
136             message: this.getMessage(root),
137             data: this.extractData(q.select(this.meta.record, root) || q.select(this.meta.root, root), false),
138             raw: doc
139         });
140
141         if (Ext.isEmpty(res.success)) {
142             throw new Ext.data.DataReader.Error('successProperty-response', this.meta.successProperty);
143         }
144
145         // Create actions from a response having status 200 must return pk
146         if (action === Ext.data.Api.actions.create) {
147             var def = Ext.isDefined(res.data);
148             if (def && Ext.isEmpty(res.data)) {
149                 throw new Ext.data.JsonReader.Error('root-empty', this.meta.root);
150             }
151             else if (!def) {
152                 throw new Ext.data.JsonReader.Error('root-undefined-response', this.meta.root);
153             }
154         }
155         return res;
156     },
157
158     getSuccess : function() {
159         return true;
160     },
161
162     /**
163      * build response-data extractor functions.
164      * @private
165      * @ignore
166      */
167     buildExtractors : function() {
168         if(this.ef){
169             return;
170         }
171         var s       = this.meta,
172             Record  = this.recordType,
173             f       = Record.prototype.fields,
174             fi      = f.items,
175             fl      = f.length;
176
177         if(s.totalProperty) {
178             this.getTotal = this.createAccessor(s.totalProperty);
179         }
180         if(s.successProperty) {
181             this.getSuccess = this.createAccessor(s.successProperty);
182         }
183         if (s.messageProperty) {
184             this.getMessage = this.createAccessor(s.messageProperty);
185         }
186         this.getRoot = function(res) {
187             return (!Ext.isEmpty(res[this.meta.record])) ? res[this.meta.record] : res[this.meta.root];
188         };
189         if (s.idPath || s.idProperty) {
190             var g = this.createAccessor(s.idPath || s.idProperty);
191             this.getId = function(rec) {
192                 var id = g(rec) || rec.id;
193                 return (id === undefined || id === '') ? null : id;
194             };
195         } else {
196             this.getId = function(){return null;};
197         }
198         var ef = [];
199         for(var i = 0; i < fl; i++){
200             f = fi[i];
201             var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
202             ef.push(this.createAccessor(map));
203         }
204         this.ef = ef;
205     },
206
207     /**
208      * Creates a function to return some particular key of data from a response.
209      * @param {String} key
210      * @return {Function}
211      * @private
212      * @ignore
213      */
214     createAccessor : function(){
215         var q = Ext.DomQuery;
216         return function(key) {
217             if (Ext.isFunction(key)) {
218                 return key;
219             }
220             switch(key) {
221                 case this.meta.totalProperty:
222                     return function(root, def){
223                         return q.selectNumber(key, root, def);
224                     };
225                     break;
226                 case this.meta.successProperty:
227                     return function(root, def) {
228                         var sv = q.selectValue(key, root, true);
229                         var success = sv !== false && sv !== 'false';
230                         return success;
231                     };
232                     break;
233                 default:
234                     return function(root, def) {
235                         return q.selectValue(key, root, def);
236                     };
237                     break;
238             }
239         };
240     }(),
241
242     /**
243      * extracts values and type-casts a row of data from server, extracted by #extractData
244      * @param {Hash} data
245      * @param {Ext.data.Field[]} items
246      * @param {Number} len
247      * @private
248      * @ignore
249      */
250     extractValues : function(data, items, len) {
251         var f, values = {};
252         for(var j = 0; j < len; j++){
253             f = items[j];
254             var v = this.ef[j](data);
255             values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue, data);
256         }
257         return values;
258     }
259 });