Upgrade to ExtJS 3.1.1 - Released 02/08/2010
[extjs.git] / src / data / HttpProxy.js
1 /*!
2  * Ext JS Library 3.1.1
3  * Copyright(c) 2006-2010 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 (<code>this</code> reference) in which the callback function is executed. Defaults to the browser window.\r
99      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.\r
100      * @protected\r
101      */\r
102     doRequest : function(action, rs, params, reader, cb, scope, arg) {\r
103         var  o = {\r
104             method: (this.api[action]) ? this.api[action]['method'] : undefined,\r
105             request: {\r
106                 callback : cb,\r
107                 scope : scope,\r
108                 arg : arg\r
109             },\r
110             reader: reader,\r
111             callback : this.createCallback(action, rs),\r
112             scope: this\r
113         };\r
114 \r
115         // If possible, transmit data using jsonData || xmlData on Ext.Ajax.request (An installed DataWriter would have written it there.).\r
116         // Use std HTTP params otherwise.\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 must have overridden the url during a beforewrite/beforeload event-handler.\r
126         // this.conn.url is nullified after each request.\r
127         this.conn.url = this.buildUrl(action, rs);\r
128 \r
129         if(this.useAjax){\r
130 \r
131             Ext.applyIf(o, this.conn);\r
132 \r
133             // If a currently running request is found for this action, abort it.\r
134             if (this.activeRequest[action]) {\r
135                 ////\r
136                 // Disabled aborting activeRequest while implementing REST.  activeRequest[action] will have to become an array\r
137                 // TODO ideas anyone?\r
138                 //\r
139                 //Ext.Ajax.abort(this.activeRequest[action]);\r
140             }\r
141             this.activeRequest[action] = Ext.Ajax.request(o);\r
142         }else{\r
143             this.conn.request(o);\r
144         }\r
145         // request is sent, nullify the connection url in preparation for the next request\r
146         this.conn.url = null;\r
147     },\r
148 \r
149     /**\r
150      * Returns a callback function for a request.  Note a special case is made for the\r
151      * read action vs all the others.\r
152      * @param {String} action [create|update|delete|load]\r
153      * @param {Ext.data.Record[]} rs The Store-recordset being acted upon\r
154      * @private\r
155      */\r
156     createCallback : function(action, rs) {\r
157         return function(o, success, response) {\r
158             this.activeRequest[action] = undefined;\r
159             if (!success) {\r
160                 if (action === Ext.data.Api.actions.read) {\r
161                     // @deprecated: fire loadexception for backwards compat.\r
162                     // TODO remove in 3.1\r
163                     this.fireEvent('loadexception', this, o, response);\r
164                 }\r
165                 this.fireEvent('exception', this, 'response', action, o, response);\r
166                 o.request.callback.call(o.request.scope, null, o.request.arg, false);\r
167                 return;\r
168             }\r
169             if (action === Ext.data.Api.actions.read) {\r
170                 this.onRead(action, o, response);\r
171             } else {\r
172                 this.onWrite(action, o, response, rs);\r
173             }\r
174         };\r
175     },\r
176 \r
177     /**\r
178      * Callback for read action\r
179      * @param {String} action Action name as per {@link Ext.data.Api.actions#read}.\r
180      * @param {Object} o The request transaction object\r
181      * @param {Object} res The server response\r
182      * @fires loadexception (deprecated)\r
183      * @fires exception\r
184      * @fires load\r
185      * @protected\r
186      */\r
187     onRead : function(action, o, response) {\r
188         var result;\r
189         try {\r
190             result = o.reader.read(response);\r
191         }catch(e){\r
192             // @deprecated: fire old loadexception for backwards-compat.\r
193             // TODO remove in 3.1\r
194             this.fireEvent('loadexception', this, o, response, e);\r
195 \r
196             this.fireEvent('exception', this, 'response', action, o, response, e);\r
197             o.request.callback.call(o.request.scope, null, o.request.arg, false);\r
198             return;\r
199         }\r
200         if (result.success === false) {\r
201             // @deprecated: fire old loadexception for backwards-compat.\r
202             // TODO remove in 3.1\r
203             this.fireEvent('loadexception', this, o, response);\r
204 \r
205             // Get DataReader read-back a response-object to pass along to exception event\r
206             var res = o.reader.readResponse(action, response);\r
207             this.fireEvent('exception', this, 'remote', action, o, res, null);\r
208         }\r
209         else {\r
210             this.fireEvent('load', this, o, o.request.arg);\r
211         }\r
212         // TODO refactor onRead, onWrite to be more generalized now that we're dealing with Ext.data.Response instance\r
213         // the calls to request.callback(...) in each will have to be made identical.\r
214         // NOTE reader.readResponse does not currently return Ext.data.Response\r
215         o.request.callback.call(o.request.scope, result, o.request.arg, result.success);\r
216     },\r
217     /**\r
218      * Callback for write actions\r
219      * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]\r
220      * @param {Object} trans The request transaction object\r
221      * @param {Object} res The server response\r
222      * @fires exception\r
223      * @fires write\r
224      * @protected\r
225      */\r
226     onWrite : function(action, o, response, rs) {\r
227         var reader = o.reader;\r
228         var res;\r
229         try {\r
230             res = reader.readResponse(action, response);\r
231         } catch (e) {\r
232             this.fireEvent('exception', this, 'response', action, o, response, e);\r
233             o.request.callback.call(o.request.scope, null, o.request.arg, false);\r
234             return;\r
235         }\r
236         if (res.success === true) {\r
237             this.fireEvent('write', this, action, res.data, res, rs, o.request.arg);\r
238         } else {\r
239             this.fireEvent('exception', this, 'remote', action, o, res, rs);\r
240         }\r
241         // TODO refactor onRead, onWrite to be more generalized now that we're dealing with Ext.data.Response instance\r
242         // the calls to request.callback(...) in each will have to be made similar.\r
243         // NOTE reader.readResponse does not currently return Ext.data.Response\r
244         o.request.callback.call(o.request.scope, res.data, res, res.success);\r
245     },\r
246 \r
247     // inherit docs\r
248     destroy: function(){\r
249         if(!this.useAjax){\r
250             this.conn.abort();\r
251         }else if(this.activeRequest){\r
252             var actions = Ext.data.Api.actions;\r
253             for (var verb in actions) {\r
254                 if(this.activeRequest[actions[verb]]){\r
255                     Ext.Ajax.abort(this.activeRequest[actions[verb]]);\r
256                 }\r
257             }\r
258         }\r
259         Ext.data.HttpProxy.superclass.destroy.call(this);\r
260     }\r
261 });