Upgrade to ExtJS 3.0.0 - Released 07/06/2009
[extjs.git] / src / data / HttpProxy.js
1 /*!
2  * Ext JS Library 3.0.0
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, beforesave, etc).  The connection url will be nullified\r
42     // after each request as well.  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     //private.  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      * @cfg {Boolean} restful\r
58      * <p>If set to <tt>true</tt>, a {@link Ext.data.Record#phantom non-phantom} record's\r
59      * {@link Ext.data.Record#id id} will be appended to the url (defaults to <tt>false</tt>).</p><br>\r
60      * <p>The url is built based upon the action being executed <tt>[load|create|save|destroy]</tt>\r
61      * using the commensurate <tt>{@link #api}</tt> property, or if undefined default to the\r
62      * configured {@link Ext.data.Store}.{@link Ext.data.Store#url url}.</p><br>\r
63      * <p>Some MVC (e.g., Ruby on Rails, Merb and Django) support this style of segment based urls\r
64      * where the segments in the URL follow the Model-View-Controller approach.</p><pre><code>\r
65      * someSite.com/controller/action/id\r
66      * </code></pre>\r
67      * Where the segments in the url are typically:<div class="mdetail-params"><ul>\r
68      * <li>The first segment : represents the controller class that should be invoked.</li>\r
69      * <li>The second segment : represents the class function, or method, that should be called.</li>\r
70      * <li>The third segment : represents the ID (a variable typically passed to the method).</li>\r
71      * </ul></div></p>\r
72      * <p>For example:</p>\r
73      * <pre><code>\r
74 api: {\r
75     load :    '/controller/load',\r
76     create :  '/controller/new',  // Server MUST return idProperty of new record\r
77     save :    '/controller/update',\r
78     destroy : '/controller/destroy_action'\r
79 }\r
80 \r
81 // Alternatively, one can use the object-form to specify each API-action\r
82 api: {\r
83     load: {url: 'read.php', method: 'GET'},\r
84     create: 'create.php',\r
85     destroy: 'destroy.php',\r
86     save: 'update.php'\r
87 }\r
88      */\r
89 \r
90     /**\r
91      * Return the {@link Ext.data.Connection} object being used by this Proxy.\r
92      * @return {Connection} The Connection object. This object may be used to subscribe to events on\r
93      * a finer-grained basis than the DataProxy events.\r
94      */\r
95     getConnection : function() {\r
96         return this.useAjax ? Ext.Ajax : this.conn;\r
97     },\r
98 \r
99     /**\r
100      * Used for overriding the url used for a single request.  Designed to be called during a beforeaction event.  Calling setUrl\r
101      * will override any urls set via the api configuration parameter.  Set the optional parameter makePermanent to set the url for\r
102      * all subsequent requests.  If not set to makePermanent, the next request will use the same url or api configuration defined\r
103      * in the initial proxy configuration.\r
104      * @param {String} url\r
105      * @param {Boolean} makePermanent (Optional) [false]\r
106      *\r
107      * (e.g.: beforeload, beforesave, etc).\r
108      */\r
109     setUrl : function(url, makePermanent) {\r
110         this.conn.url = url;\r
111         if (makePermanent === true) {\r
112             this.url = url;\r
113             Ext.data.Api.prepare(this);\r
114         }\r
115     },\r
116 \r
117     /**\r
118      * HttpProxy implementation of DataProxy#doRequest\r
119      * @param {String} action The crud action type (create, read, update, destroy)\r
120      * @param {Ext.data.Record/Ext.data.Record[]} rs If action is load, rs will be null\r
121      * @param {Object} params An object containing properties which are to be used as HTTP parameters\r
122      * for the request to the remote server.\r
123      * @param {Ext.data.DataReader} reader The Reader object which converts the data\r
124      * object into a block of Ext.data.Records.\r
125      * @param {Function} callback\r
126      * <div class="sub-desc"><p>A function to be called after the request.\r
127      * The <tt>callback</tt> is passed the following arguments:<ul>\r
128      * <li><tt>r</tt> : Ext.data.Record[] The block of Ext.data.Records.</li>\r
129      * <li><tt>options</tt>: Options object from the action request</li>\r
130      * <li><tt>success</tt>: Boolean success indicator</li></ul></p></div>\r
131      * @param {Object} scope The scope in which to call the callback\r
132      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.\r
133      */\r
134     doRequest : function(action, rs, params, reader, cb, scope, arg) {\r
135         var  o = {\r
136             method: (this.api[action]) ? this.api[action]['method'] : undefined,\r
137             request: {\r
138                 callback : cb,\r
139                 scope : scope,\r
140                 arg : arg\r
141             },\r
142             reader: reader,\r
143             callback : this.createCallback(action, rs),\r
144             scope: this\r
145         };\r
146         // Sample the request data:  If it's an object, then it hasn't been json-encoded yet.\r
147         // Transmit data using jsonData config of Ext.Ajax.request\r
148         if (typeof(params[reader.meta.root]) === 'object') {\r
149             o.jsonData = params;\r
150         } else {\r
151             o.params = params || {};\r
152         }\r
153         // Set the connection url.  If this.conn.url is not null here,\r
154         // the user may have overridden the url during a beforeaction event-handler.\r
155         // this.conn.url is nullified after each request.\r
156         if (this.conn.url === null) {\r
157             this.conn.url = this.buildUrl(action, rs);\r
158         }\r
159         else if (this.restful === true && rs instanceof Ext.data.Record && !rs.phantom) {\r
160             this.conn.url += '/' + rs.id;\r
161         }\r
162         if(this.useAjax){\r
163 \r
164             Ext.applyIf(o, this.conn);\r
165 \r
166             // If a currently running request is found for this action, abort it.\r
167             if (this.activeRequest[action]) {\r
168                 // Disabled aborting activeRequest while implementing REST.  activeRequest[action] will have to become an array\r
169                 //Ext.Ajax.abort(this.activeRequest[action]);\r
170             }\r
171             this.activeRequest[action] = Ext.Ajax.request(o);\r
172         }else{\r
173             this.conn.request(o);\r
174         }\r
175         // request is sent, nullify the connection url in preparation for the next request\r
176         this.conn.url = null;\r
177     },\r
178 \r
179     /**\r
180      * Returns a callback function for a request.  Note a special case is made for the\r
181      * read action vs all the others.\r
182      * @param {String} action [create|update|delete|load]\r
183      * @param {Ext.data.Record[]} rs The Store-recordset being acted upon\r
184      * @private\r
185      */\r
186     createCallback : function(action, rs) {\r
187         return function(o, success, response) {\r
188             this.activeRequest[action] = undefined;\r
189             if (!success) {\r
190                 if (action === Ext.data.Api.actions.read) {\r
191                     // @deprecated: fire loadexception for backwards compat.\r
192                     this.fireEvent('loadexception', this, o, response);\r
193                 }\r
194                 this.fireEvent('exception', this, 'response', action, o, response);\r
195                 o.request.callback.call(o.request.scope, null, o.request.arg, false);\r
196                 return;\r
197             }\r
198             if (action === Ext.data.Api.actions.read) {\r
199                 this.onRead(action, o, response);\r
200             } else {\r
201                 this.onWrite(action, o, response, rs);\r
202             }\r
203         }\r
204     },\r
205 \r
206     /**\r
207      * Callback for read action\r
208      * @param {String} action Action name as per {@link Ext.data.Api.actions#read}.\r
209      * @param {Object} o The request transaction object\r
210      * @param {Object} res The server response\r
211      * @private\r
212      */\r
213     onRead : function(action, o, response) {\r
214         var result;\r
215         try {\r
216             result = o.reader.read(response);\r
217         }catch(e){\r
218             // @deprecated: fire old loadexception for backwards-compat.\r
219             this.fireEvent('loadexception', this, o, response, e);\r
220             this.fireEvent('exception', this, 'response', action, o, response, e);\r
221             o.request.callback.call(o.request.scope, null, o.request.arg, false);\r
222             return;\r
223         }\r
224         if (result.success === false) {\r
225             // @deprecated: fire old loadexception for backwards-compat.\r
226             this.fireEvent('loadexception', this, o, response);\r
227 \r
228             // Get DataReader read-back a response-object to pass along to exception event\r
229             var res = o.reader.readResponse(action, response);\r
230             this.fireEvent('exception', this, 'remote', action, o, res, null);\r
231         }\r
232         else {\r
233             this.fireEvent('load', this, o, o.request.arg);\r
234         }\r
235         o.request.callback.call(o.request.scope, result, o.request.arg, result.success);\r
236     },\r
237     /**\r
238      * Callback for write actions\r
239      * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]\r
240      * @param {Object} trans The request transaction object\r
241      * @param {Object} res The server response\r
242      * @private\r
243      */\r
244     onWrite : function(action, o, response, rs) {\r
245         var reader = o.reader;\r
246         var res;\r
247         try {\r
248             res = reader.readResponse(action, response);\r
249         } catch (e) {\r
250             this.fireEvent('exception', this, 'response', action, o, response, e);\r
251             o.request.callback.call(o.request.scope, null, o.request.arg, false);\r
252             return;\r
253         }\r
254         if (res[reader.meta.successProperty] === false) {\r
255             this.fireEvent('exception', this, 'remote', action, o, res, rs);\r
256         } else {\r
257             this.fireEvent('write', this, action, res[reader.meta.root], res, rs, o.request.arg);\r
258         }\r
259         o.request.callback.call(o.request.scope, res[reader.meta.root], res, res[reader.meta.successProperty]);\r
260     },\r
261 \r
262     // inherit docs\r
263     destroy: function(){\r
264         if(!this.useAjax){\r
265             this.conn.abort();\r
266         }else if(this.activeRequest){\r
267             var actions = Ext.data.Api.actions;\r
268             for (var verb in actions) {\r
269                 if(this.activeRequest[actions[verb]]){\r
270                     Ext.Ajax.abort(this.activeRequest[actions[verb]]);\r
271                 }\r
272             }\r
273         }\r
274         Ext.data.HttpProxy.superclass.destroy.call(this);\r
275     }\r
276 });