Upgrade to ExtJS 3.0.3 - Released 10/11/2009
[extjs.git] / src / data / HttpProxy.js
1 /*!
2  * Ext JS Library 3.0.3
3  * Copyright(c) 2006-2009 Ext JS, LLC
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**\r
8  * @class Ext.data.HttpProxy\r
9  * @extends Ext.data.DataProxy\r
10  * <p>An implementation of {@link Ext.data.DataProxy} that processes data requests within the same\r
11  * domain of the originating page.</p>\r
12  * <p><b>Note</b>: this class cannot be used to retrieve data from a domain other\r
13  * than the domain from which the running page was served. For cross-domain requests, use a\r
14  * {@link Ext.data.ScriptTagProxy ScriptTagProxy}.</p>\r
15  * <p>Be aware that to enable the browser to parse an XML document, the server must set\r
16  * the Content-Type header in the HTTP response to "<tt>text/xml</tt>".</p>\r
17  * @constructor\r
18  * @param {Object} conn\r
19  * An {@link Ext.data.Connection} object, or options parameter to {@link Ext.Ajax#request}.\r
20  * <p>Note that if this HttpProxy is being used by a (@link Ext.data.Store Store}, then the\r
21  * Store's call to {@link #load} will override any specified <tt>callback</tt> and <tt>params</tt>\r
22  * options. In this case, use the Store's {@link Ext.data.Store#events events} to modify parameters,\r
23  * or react to loading events. The Store's {@link Ext.data.Store#baseParams baseParams} may also be\r
24  * used to pass parameters known at instantiation time.</p>\r
25  * <p>If an options parameter is passed, the singleton {@link Ext.Ajax} object will be used to make\r
26  * the request.</p>\r
27  */\r
28 Ext.data.HttpProxy = function(conn){\r
29     Ext.data.HttpProxy.superclass.constructor.call(this, conn);\r
30 \r
31     /**\r
32      * The Connection object (Or options parameter to {@link Ext.Ajax#request}) which this HttpProxy\r
33      * uses to make requests to the server. Properties of this object may be changed dynamically to\r
34      * change the way data is requested.\r
35      * @property\r
36      */\r
37     this.conn = conn;\r
38 \r
39     // nullify the connection url.  The url param has been copied to 'this' above.  The connection\r
40     // url will be set during each execution of doRequest when buildUrl is called.  This makes it easier for users to override the\r
41     // connection url during beforeaction events (ie: beforeload, beforewrite, etc).\r
42     // Url is always re-defined during doRequest.\r
43     this.conn.url = null;\r
44 \r
45     this.useAjax = !conn || !conn.events;\r
46 \r
47     // A hash containing active requests, keyed on action [Ext.data.Api.actions.create|read|update|destroy]\r
48     var actions = Ext.data.Api.actions;\r
49     this.activeRequest = {};\r
50     for (var verb in actions) {\r
51         this.activeRequest[actions[verb]] = undefined;\r
52     }\r
53 };\r
54 \r
55 Ext.extend(Ext.data.HttpProxy, Ext.data.DataProxy, {\r
56     /**\r
57      * Return the {@link Ext.data.Connection} object being used by this Proxy.\r
58      * @return {Connection} The Connection object. This object may be used to subscribe to events on\r
59      * a finer-grained basis than the DataProxy events.\r
60      */\r
61     getConnection : function() {\r
62         return this.useAjax ? Ext.Ajax : this.conn;\r
63     },\r
64 \r
65     /**\r
66      * Used for overriding the url used for a single request.  Designed to be called during a beforeaction event.  Calling setUrl\r
67      * will override any urls set via the api configuration parameter.  Set the optional parameter makePermanent to set the url for\r
68      * all subsequent requests.  If not set to makePermanent, the next request will use the same url or api configuration defined\r
69      * in the initial proxy configuration.\r
70      * @param {String} url\r
71      * @param {Boolean} makePermanent (Optional) [false]\r
72      *\r
73      * (e.g.: beforeload, beforesave, etc).\r
74      */\r
75     setUrl : function(url, makePermanent) {\r
76         this.conn.url = url;\r
77         if (makePermanent === true) {\r
78             this.url = url;\r
79             this.api = null;\r
80             Ext.data.Api.prepare(this);\r
81         }\r
82     },\r
83 \r
84     /**\r
85      * HttpProxy implementation of DataProxy#doRequest\r
86      * @param {String} action The crud action type (create, read, update, destroy)\r
87      * @param {Ext.data.Record/Ext.data.Record[]} rs If action is load, rs will be null\r
88      * @param {Object} params An object containing properties which are to be used as HTTP parameters\r
89      * for the request to the remote server.\r
90      * @param {Ext.data.DataReader} reader The Reader object which converts the data\r
91      * object into a block of Ext.data.Records.\r
92      * @param {Function} callback\r
93      * <div class="sub-desc"><p>A function to be called after the request.\r
94      * The <tt>callback</tt> is passed the following arguments:<ul>\r
95      * <li><tt>r</tt> : Ext.data.Record[] The block of Ext.data.Records.</li>\r
96      * <li><tt>options</tt>: Options object from the action request</li>\r
97      * <li><tt>success</tt>: Boolean success indicator</li></ul></p></div>\r
98      * @param {Object} scope The scope in which to call the callback\r
99      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.\r
100      */\r
101     doRequest : function(action, rs, params, reader, cb, scope, arg) {\r
102         var  o = {\r
103             method: (this.api[action]) ? this.api[action]['method'] : undefined,\r
104             request: {\r
105                 callback : cb,\r
106                 scope : scope,\r
107                 arg : arg\r
108             },\r
109             reader: reader,\r
110             callback : this.createCallback(action, rs),\r
111             scope: this\r
112         };\r
113 \r
114         // If possible, transmit data using jsonData || xmlData on Ext.Ajax.request (An installed DataWriter would have written it there.).\r
115         // Use std HTTP params otherwise.\r
116         // TODO wrap into 1 Ext.apply now?\r
117         if (params.jsonData) {\r
118             o.jsonData = params.jsonData;\r
119         } else if (params.xmlData) {\r
120             o.xmlData = params.xmlData;\r
121         } else {\r
122             o.params = params || {};\r
123         }\r
124         // Set the connection url.  If this.conn.url is not null here,\r
125         // the user may have overridden the url during a beforeaction event-handler.\r
126         // this.conn.url is nullified after each request.\r
127         if (this.conn.url === null) {\r
128             this.conn.url = this.buildUrl(action, rs);\r
129         }\r
130         else if (this.restful === true && rs instanceof Ext.data.Record && !rs.phantom) { // <-- user must have intervened with #setApi or #setUrl\r
131             this.conn.url += '/' + rs.id;\r
132         }\r
133         if(this.useAjax){\r
134 \r
135             Ext.applyIf(o, this.conn);\r
136 \r
137             // If a currently running request is found for this action, abort it.\r
138             if (this.activeRequest[action]) {\r
139                 ////\r
140                 // Disabled aborting activeRequest while implementing REST.  activeRequest[action] will have to become an array\r
141                 // TODO ideas anyone?\r
142                 //\r
143                 //Ext.Ajax.abort(this.activeRequest[action]);\r
144             }\r
145             this.activeRequest[action] = Ext.Ajax.request(o);\r
146         }else{\r
147             this.conn.request(o);\r
148         }\r
149         // request is sent, nullify the connection url in preparation for the next request\r
150         this.conn.url = null;\r
151     },\r
152 \r
153     /**\r
154      * Returns a callback function for a request.  Note a special case is made for the\r
155      * read action vs all the others.\r
156      * @param {String} action [create|update|delete|load]\r
157      * @param {Ext.data.Record[]} rs The Store-recordset being acted upon\r
158      * @private\r
159      */\r
160     createCallback : function(action, rs) {\r
161         return function(o, success, response) {\r
162             this.activeRequest[action] = undefined;\r
163             if (!success) {\r
164                 if (action === Ext.data.Api.actions.read) {\r
165                     // @deprecated: fire loadexception for backwards compat.\r
166                     // TODO remove in 3.1\r
167                     this.fireEvent('loadexception', this, o, response);\r
168                 }\r
169                 this.fireEvent('exception', this, 'response', action, o, response);\r
170                 o.request.callback.call(o.request.scope, null, o.request.arg, false);\r
171                 return;\r
172             }\r
173             if (action === Ext.data.Api.actions.read) {\r
174                 this.onRead(action, o, response);\r
175             } else {\r
176                 this.onWrite(action, o, response, rs);\r
177             }\r
178         }\r
179     },\r
180 \r
181     /**\r
182      * Callback for read action\r
183      * @param {String} action Action name as per {@link Ext.data.Api.actions#read}.\r
184      * @param {Object} o The request transaction object\r
185      * @param {Object} res The server response\r
186      * @fires loadexception (deprecated)\r
187      * @fires exception\r
188      * @fires load\r
189      * @private\r
190      */\r
191     onRead : function(action, o, response) {\r
192         var result;\r
193         try {\r
194             result = o.reader.read(response);\r
195         }catch(e){\r
196             // @deprecated: fire old loadexception for backwards-compat.\r
197             // TODO remove in 3.1\r
198             this.fireEvent('loadexception', this, o, response, e);\r
199 \r
200             this.fireEvent('exception', this, 'response', action, o, response, e);\r
201             o.request.callback.call(o.request.scope, null, o.request.arg, false);\r
202             return;\r
203         }\r
204         if (result.success === false) {\r
205             // @deprecated: fire old loadexception for backwards-compat.\r
206             // TODO remove in 3.1\r
207             this.fireEvent('loadexception', this, o, response);\r
208 \r
209             // Get DataReader read-back a response-object to pass along to exception event\r
210             var res = o.reader.readResponse(action, response);\r
211             this.fireEvent('exception', this, 'remote', action, o, res, null);\r
212         }\r
213         else {\r
214             this.fireEvent('load', this, o, o.request.arg);\r
215         }\r
216         // TODO refactor onRead, onWrite to be more generalized now that we're dealing with Ext.data.Response instance\r
217         // the calls to request.callback(...) in each will have to be made identical.\r
218         // NOTE reader.readResponse does not currently return Ext.data.Response\r
219         o.request.callback.call(o.request.scope, result, o.request.arg, result.success);\r
220     },\r
221     /**\r
222      * Callback for write actions\r
223      * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]\r
224      * @param {Object} trans The request transaction object\r
225      * @param {Object} res The server response\r
226      * @fires exception\r
227      * @fires write\r
228      * @private\r
229      */\r
230     onWrite : function(action, o, response, rs) {\r
231         var reader = o.reader;\r
232         var res;\r
233         try {\r
234             res = reader.readResponse(action, response);\r
235         } catch (e) {\r
236             this.fireEvent('exception', this, 'response', action, o, response, e);\r
237             o.request.callback.call(o.request.scope, null, o.request.arg, false);\r
238             return;\r
239         }\r
240         if (res.success === false) {\r
241             this.fireEvent('exception', this, 'remote', action, o, res, rs);\r
242         } else {\r
243             this.fireEvent('write', this, action, res.data, res, rs, o.request.arg);\r
244         }\r
245         // TODO refactor onRead, onWrite to be more generalized now that we're dealing with Ext.data.Response instance\r
246         // the calls to request.callback(...) in each will have to be made similar.\r
247         // NOTE reader.readResponse does not currently return Ext.data.Response\r
248         o.request.callback.call(o.request.scope, res.data, res, res.success);\r
249     },\r
250 \r
251     // inherit docs\r
252     destroy: function(){\r
253         if(!this.useAjax){\r
254             this.conn.abort();\r
255         }else if(this.activeRequest){\r
256             var actions = Ext.data.Api.actions;\r
257             for (var verb in actions) {\r
258                 if(this.activeRequest[actions[verb]]){\r
259                     Ext.Ajax.abort(this.activeRequest[actions[verb]]);\r
260                 }\r
261             }\r
262         }\r
263         Ext.data.HttpProxy.superclass.destroy.call(this);\r
264     }\r
265 });