Upgrade to ExtJS 3.2.0 - Released 03/30/2010
[extjs.git] / src / data / DataReader.js
1 /*!
2  * Ext JS Library 3.2.0
3  * Copyright(c) 2006-2010 Ext JS, Inc.
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**
8  * @class Ext.data.DataReader
9  * Abstract base class for reading structured data from a data source and converting
10  * it into an object containing {@link Ext.data.Record} objects and metadata for use
11  * by an {@link Ext.data.Store}.  This class is intended to be extended and should not
12  * be created directly. For existing implementations, see {@link Ext.data.ArrayReader},
13  * {@link Ext.data.JsonReader} and {@link Ext.data.XmlReader}.
14  * @constructor Create a new DataReader
15  * @param {Object} meta Metadata configuration options (implementation-specific).
16  * @param {Array/Object} recordType
17  * <p>Either an Array of {@link Ext.data.Field Field} definition objects (which
18  * will be passed to {@link Ext.data.Record#create}, or a {@link Ext.data.Record Record}
19  * constructor created using {@link Ext.data.Record#create}.</p>
20  */
21 Ext.data.DataReader = function(meta, recordType){
22     /**
23      * This DataReader's configured metadata as passed to the constructor.
24      * @type Mixed
25      * @property meta
26      */
27     this.meta = meta;
28     /**
29      * @cfg {Array/Object} fields
30      * <p>Either an Array of {@link Ext.data.Field Field} definition objects (which
31      * will be passed to {@link Ext.data.Record#create}, or a {@link Ext.data.Record Record}
32      * constructor created from {@link Ext.data.Record#create}.</p>
33      */
34     this.recordType = Ext.isArray(recordType) ?
35         Ext.data.Record.create(recordType) : recordType;
36
37     // if recordType defined make sure extraction functions are defined
38     if (this.recordType){
39         this.buildExtractors();
40     }
41 };
42
43 Ext.data.DataReader.prototype = {
44     /**
45      * @cfg {String} messageProperty [undefined] Optional name of a property within a server-response that represents a user-feedback message.
46      */
47     /**
48      * Abstract method created in extension's buildExtractors impl.
49      */
50     getTotal: Ext.emptyFn,
51     /**
52      * Abstract method created in extension's buildExtractors impl.
53      */
54     getRoot: Ext.emptyFn,
55     /**
56      * Abstract method created in extension's buildExtractors impl.
57      */
58     getMessage: Ext.emptyFn,
59     /**
60      * Abstract method created in extension's buildExtractors impl.
61      */
62     getSuccess: Ext.emptyFn,
63     /**
64      * Abstract method created in extension's buildExtractors impl.
65      */
66     getId: Ext.emptyFn,
67     /**
68      * Abstract method, overridden in DataReader extensions such as {@link Ext.data.JsonReader} and {@link Ext.data.XmlReader}
69      */
70     buildExtractors : Ext.emptyFn,
71     /**
72      * Abstract method overridden in DataReader extensions such as {@link Ext.data.JsonReader} and {@link Ext.data.XmlReader}
73      */
74     extractValues : Ext.emptyFn,
75
76     /**
77      * Used for un-phantoming a record after a successful database insert.  Sets the records pk along with new data from server.
78      * You <b>must</b> return at least the database pk using the idProperty defined in your DataReader configuration.  The incoming
79      * data from server will be merged with the data in the local record.
80      * In addition, you <b>must</b> return record-data from the server in the same order received.
81      * Will perform a commit as well, un-marking dirty-fields.  Store's "update" event will be suppressed.
82      * @param {Record/Record[]} record The phantom record to be realized.
83      * @param {Object/Object[]} data The new record data to apply.  Must include the primary-key from database defined in idProperty field.
84      */
85     realize: function(rs, data){
86         if (Ext.isArray(rs)) {
87             for (var i = rs.length - 1; i >= 0; i--) {
88                 // recurse
89                 if (Ext.isArray(data)) {
90                     this.realize(rs.splice(i,1).shift(), data.splice(i,1).shift());
91                 }
92                 else {
93                     // weird...rs is an array but data isn't??  recurse but just send in the whole invalid data object.
94                     // the else clause below will detect !this.isData and throw exception.
95                     this.realize(rs.splice(i,1).shift(), data);
96                 }
97             }
98         }
99         else {
100             // If rs is NOT an array but data IS, see if data contains just 1 record.  If so extract it and carry on.
101             if (Ext.isArray(data) && data.length == 1) {
102                 data = data.shift();
103             }
104             if (!this.isData(data)) {
105                 // TODO: Let exception-handler choose to commit or not rather than blindly rs.commit() here.
106                 //rs.commit();
107                 throw new Ext.data.DataReader.Error('realize', rs);
108             }
109             rs.phantom = false; // <-- That's what it's all about
110             rs._phid = rs.id;  // <-- copy phantom-id -> _phid, so we can remap in Store#onCreateRecords
111             rs.id = this.getId(data);
112             rs.data = data;
113
114             rs.commit();
115         }
116     },
117
118     /**
119      * Used for updating a non-phantom or "real" record's data with fresh data from server after remote-save.
120      * If returning data from multiple-records after a batch-update, you <b>must</b> return record-data from the server in
121      * the same order received.  Will perform a commit as well, un-marking dirty-fields.  Store's "update" event will be
122      * suppressed as the record receives fresh new data-hash
123      * @param {Record/Record[]} rs
124      * @param {Object/Object[]} data
125      */
126     update : function(rs, data) {
127         if (Ext.isArray(rs)) {
128             for (var i=rs.length-1; i >= 0; i--) {
129                 if (Ext.isArray(data)) {
130                     this.update(rs.splice(i,1).shift(), data.splice(i,1).shift());
131                 }
132                 else {
133                     // weird...rs is an array but data isn't??  recurse but just send in the whole data object.
134                     // the else clause below will detect !this.isData and throw exception.
135                     this.update(rs.splice(i,1).shift(), data);
136                 }
137             }
138         }
139         else {
140             // If rs is NOT an array but data IS, see if data contains just 1 record.  If so extract it and carry on.
141             if (Ext.isArray(data) && data.length == 1) {
142                 data = data.shift();
143             }
144             if (this.isData(data)) {
145                 rs.data = Ext.apply(rs.data, data);
146             }
147             rs.commit();
148         }
149     },
150
151     /**
152      * returns extracted, type-cast rows of data.  Iterates to call #extractValues for each row
153      * @param {Object[]/Object} data-root from server response
154      * @param {Boolean} returnRecords [false] Set true to return instances of Ext.data.Record
155      * @private
156      */
157     extractData : function(root, returnRecords) {
158         // A bit ugly this, too bad the Record's raw data couldn't be saved in a common property named "raw" or something.
159         var rawName = (this instanceof Ext.data.JsonReader) ? 'json' : 'node';
160
161         var rs = [];
162
163         // Had to add Check for XmlReader, #isData returns true if root is an Xml-object.  Want to check in order to re-factor
164         // #extractData into DataReader base, since the implementations are almost identical for JsonReader, XmlReader
165         if (this.isData(root) && !(this instanceof Ext.data.XmlReader)) {
166             root = [root];
167         }
168         var f       = this.recordType.prototype.fields,
169             fi      = f.items,
170             fl      = f.length,
171             rs      = [];
172         if (returnRecords === true) {
173             var Record = this.recordType;
174             for (var i = 0; i < root.length; i++) {
175                 var n = root[i];
176                 var record = new Record(this.extractValues(n, fi, fl), this.getId(n));
177                 record[rawName] = n;    // <-- There's implementation of ugly bit, setting the raw record-data.
178                 rs.push(record);
179             }
180         }
181         else {
182             for (var i = 0; i < root.length; i++) {
183                 var data = this.extractValues(root[i], fi, fl);
184                 data[this.meta.idProperty] = this.getId(root[i]);
185                 rs.push(data);
186             }
187         }
188         return rs;
189     },
190
191     /**
192      * Returns true if the supplied data-hash <b>looks</b> and quacks like data.  Checks to see if it has a key
193      * corresponding to idProperty defined in your DataReader config containing non-empty pk.
194      * @param {Object} data
195      * @return {Boolean}
196      */
197     isData : function(data) {
198         return (data && Ext.isObject(data) && !Ext.isEmpty(this.getId(data))) ? true : false;
199     },
200
201     // private function a store will createSequence upon
202     onMetaChange : function(meta){
203         delete this.ef;
204         this.meta = meta;
205         this.recordType = Ext.data.Record.create(meta.fields);
206         this.buildExtractors();
207     }
208 };
209
210 /**
211  * @class Ext.data.DataReader.Error
212  * @extends Ext.Error
213  * General error class for Ext.data.DataReader
214  */
215 Ext.data.DataReader.Error = Ext.extend(Ext.Error, {
216     constructor : function(message, arg) {
217         this.arg = arg;
218         Ext.Error.call(this, message);
219     },
220     name: 'Ext.data.DataReader'
221 });
222 Ext.apply(Ext.data.DataReader.Error.prototype, {
223     lang : {
224         'update': "#update received invalid data from server.  Please see docs for DataReader#update and review your DataReader configuration.",
225         'realize': "#realize was called with invalid remote-data.  Please see the docs for DataReader#realize and review your DataReader configuration.",
226         'invalid-response': "#readResponse received an invalid response from the server."
227     }
228 });