Upgrade to ExtJS 3.0.3 - Released 10/11/2009
[extjs.git] / src / data / DataProxy.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.DataProxy\r
9  * @extends Ext.util.Observable\r
10  * <p>Abstract base class for implementations which provide retrieval of unformatted data objects.\r
11  * This class is intended to be extended and should not be created directly. For existing implementations,\r
12  * see {@link Ext.data.DirectProxy}, {@link Ext.data.HttpProxy}, {@link Ext.data.ScriptTagProxy} and\r
13  * {@link Ext.data.MemoryProxy}.</p>\r
14  * <p>DataProxy implementations are usually used in conjunction with an implementation of {@link Ext.data.DataReader}\r
15  * (of the appropriate type which knows how to parse the data object) to provide a block of\r
16  * {@link Ext.data.Records} to an {@link Ext.data.Store}.</p>\r
17  * <p>The parameter to a DataProxy constructor may be an {@link Ext.data.Connection} or can also be the\r
18  * config object to an {@link Ext.data.Connection}.</p>\r
19  * <p>Custom implementations must implement either the <code><b>doRequest</b></code> method (preferred) or the\r
20  * <code>load</code> method (deprecated). See\r
21  * {@link Ext.data.HttpProxy}.{@link Ext.data.HttpProxy#doRequest doRequest} or\r
22  * {@link Ext.data.HttpProxy}.{@link Ext.data.HttpProxy#load load} for additional details.</p>\r
23  * <p><b><u>Example 1</u></b></p>\r
24  * <pre><code>\r
25 proxy: new Ext.data.ScriptTagProxy({\r
26     {@link Ext.data.Connection#url url}: 'http://extjs.com/forum/topics-remote.php'\r
27 }),\r
28  * </code></pre>\r
29  * <p><b><u>Example 2</u></b></p>\r
30  * <pre><code>\r
31 proxy : new Ext.data.HttpProxy({\r
32     {@link Ext.data.Connection#method method}: 'GET',\r
33     {@link Ext.data.HttpProxy#prettyUrls prettyUrls}: false,\r
34     {@link Ext.data.Connection#url url}: 'local/default.php', // see options parameter for {@link Ext.Ajax#request}\r
35     {@link #api}: {\r
36         // all actions except the following will use above url\r
37         create  : 'local/new.php',\r
38         update  : 'local/update.php'\r
39     }\r
40 }),\r
41  * </code></pre>\r
42  */\r
43 Ext.data.DataProxy = function(conn){\r
44     // make sure we have a config object here to support ux proxies.\r
45     // All proxies should now send config into superclass constructor.\r
46     conn = conn || {};\r
47 \r
48     // This line caused a bug when people use custom Connection object having its own request method.\r
49     // http://extjs.com/forum/showthread.php?t=67194.  Have to set DataProxy config\r
50     //Ext.applyIf(this, conn);\r
51 \r
52     this.api     = conn.api;\r
53     this.url     = conn.url;\r
54     this.restful = conn.restful;\r
55     this.listeners = conn.listeners;\r
56 \r
57     // deprecated\r
58     this.prettyUrls = conn.prettyUrls;\r
59 \r
60     /**\r
61      * @cfg {Object} api\r
62      * Specific urls to call on CRUD action methods "read", "create", "update" and "destroy".\r
63      * Defaults to:<pre><code>\r
64 api: {\r
65     read    : undefined,\r
66     create  : undefined,\r
67     update  : undefined,\r
68     destroy : undefined\r
69 }\r
70      * </code></pre>\r
71      * <p>The url is built based upon the action being executed <tt>[load|create|save|destroy]</tt>\r
72      * using the commensurate <tt>{@link #api}</tt> property, or if undefined default to the\r
73      * configured {@link Ext.data.Store}.{@link Ext.data.Store#url url}.</p><br>\r
74      * <p>For example:</p>\r
75      * <pre><code>\r
76 api: {\r
77     load :    '/controller/load',\r
78     create :  '/controller/new',  // Server MUST return idProperty of new record\r
79     save :    '/controller/update',\r
80     destroy : '/controller/destroy_action'\r
81 }\r
82 \r
83 // Alternatively, one can use the object-form to specify each API-action\r
84 api: {\r
85     load: {url: 'read.php', method: 'GET'},\r
86     create: 'create.php',\r
87     destroy: 'destroy.php',\r
88     save: 'update.php'\r
89 }\r
90      * </code></pre>\r
91      * <p>If the specific URL for a given CRUD action is undefined, the CRUD action request\r
92      * will be directed to the configured <tt>{@link Ext.data.Connection#url url}</tt>.</p>\r
93      * <br><p><b>Note</b>: To modify the URL for an action dynamically the appropriate API\r
94      * property should be modified before the action is requested using the corresponding before\r
95      * action event.  For example to modify the URL associated with the load action:\r
96      * <pre><code>\r
97 // modify the url for the action\r
98 myStore.on({\r
99     beforeload: {\r
100         fn: function (store, options) {\r
101             // use <tt>{@link Ext.data.HttpProxy#setUrl setUrl}</tt> to change the URL for *just* this request.\r
102             store.proxy.setUrl('changed1.php');\r
103 \r
104             // set optional second parameter to true to make this URL change\r
105             // permanent, applying this URL for all subsequent requests.\r
106             store.proxy.setUrl('changed1.php', true);\r
107 \r
108             // Altering the proxy API should be done using the public\r
109             // method <tt>{@link Ext.data.DataProxy#setApi setApi}</tt>.\r
110             store.proxy.setApi('read', 'changed2.php');\r
111 \r
112             // Or set the entire API with a config-object.\r
113             // When using the config-object option, you must redefine the <b>entire</b>\r
114             // API -- not just a specific action of it.\r
115             store.proxy.setApi({\r
116                 read    : 'changed_read.php',\r
117                 create  : 'changed_create.php',\r
118                 update  : 'changed_update.php',\r
119                 destroy : 'changed_destroy.php'\r
120             });\r
121         }\r
122     }\r
123 });\r
124      * </code></pre>\r
125      * </p>\r
126      */\r
127 \r
128     this.addEvents(\r
129         /**\r
130          * @event exception\r
131          * <p>Fires if an exception occurs in the Proxy during a remote request. This event is relayed\r
132          * through a corresponding {@link Ext.data.Store}.{@link Ext.data.Store#exception exception},\r
133          * so any Store instance may observe this event.</p>\r
134          * <p>In addition to being fired through the DataProxy instance that raised the event, this event is also fired\r
135          * through the Ext.data.DataProxy <i>class</i> to allow for centralized processing of exception events from <b>all</b>\r
136          * DataProxies by attaching a listener to the Ext.data.Proxy class itself.</p>\r
137          * <p>This event can be fired for one of two reasons:</p>\r
138          * <div class="mdetail-params"><ul>\r
139          * <li>remote-request <b>failed</b> : <div class="sub-desc">\r
140          * The server did not return status === 200.\r
141          * </div></li>\r
142          * <li>remote-request <b>succeeded</b> : <div class="sub-desc">\r
143          * The remote-request succeeded but the reader could not read the response.\r
144          * This means the server returned data, but the configured Reader threw an\r
145          * error while reading the response.  In this case, this event will be\r
146          * raised and the caught error will be passed along into this event.\r
147          * </div></li>\r
148          * </ul></div>\r
149          * <br><p>This event fires with two different contexts based upon the 2nd\r
150          * parameter <tt>type [remote|response]</tt>.  The first four parameters\r
151          * are identical between the two contexts -- only the final two parameters\r
152          * differ.</p>\r
153          * @param {DataProxy} this The proxy that sent the request\r
154          * @param {String} type\r
155          * <p>The value of this parameter will be either <tt>'response'</tt> or <tt>'remote'</tt>.</p>\r
156          * <div class="mdetail-params"><ul>\r
157          * <li><b><tt>'response'</tt></b> : <div class="sub-desc">\r
158          * <p>An <b>invalid</b> response from the server was returned: either 404,\r
159          * 500 or the response meta-data does not match that defined in the DataReader\r
160          * (e.g.: root, idProperty, successProperty).</p>\r
161          * </div></li>\r
162          * <li><b><tt>'remote'</tt></b> : <div class="sub-desc">\r
163          * <p>A <b>valid</b> response was returned from the server having\r
164          * successProperty === false.  This response might contain an error-message\r
165          * sent from the server.  For example, the user may have failed\r
166          * authentication/authorization or a database validation error occurred.</p>\r
167          * </div></li>\r
168          * </ul></div>\r
169          * @param {String} action Name of the action (see {@link Ext.data.Api#actions}.\r
170          * @param {Object} options The options for the action that were specified in the {@link #request}.\r
171          * @param {Object} response\r
172          * <p>The value of this parameter depends on the value of the <code>type</code> parameter:</p>\r
173          * <div class="mdetail-params"><ul>\r
174          * <li><b><tt>'response'</tt></b> : <div class="sub-desc">\r
175          * <p>The raw browser response object (e.g.: XMLHttpRequest)</p>\r
176          * </div></li>\r
177          * <li><b><tt>'remote'</tt></b> : <div class="sub-desc">\r
178          * <p>The decoded response object sent from the server.</p>\r
179          * </div></li>\r
180          * </ul></div>\r
181          * @param {Mixed} arg\r
182          * <p>The type and value of this parameter depends on the value of the <code>type</code> parameter:</p>\r
183          * <div class="mdetail-params"><ul>\r
184          * <li><b><tt>'response'</tt></b> : Error<div class="sub-desc">\r
185          * <p>The JavaScript Error object caught if the configured Reader could not read the data.\r
186          * If the remote request returns success===false, this parameter will be null.</p>\r
187          * </div></li>\r
188          * <li><b><tt>'remote'</tt></b> : Record/Record[]<div class="sub-desc">\r
189          * <p>This parameter will only exist if the <tt>action</tt> was a <b>write</b> action\r
190          * (Ext.data.Api.actions.create|update|destroy).</p>\r
191          * </div></li>\r
192          * </ul></div>\r
193          */\r
194         'exception',\r
195         /**\r
196          * @event beforeload\r
197          * Fires before a request to retrieve a data object.\r
198          * @param {DataProxy} this The proxy for the request\r
199          * @param {Object} params The params object passed to the {@link #request} function\r
200          */\r
201         'beforeload',\r
202         /**\r
203          * @event load\r
204          * Fires before the load method's callback is called.\r
205          * @param {DataProxy} this The proxy for the request\r
206          * @param {Object} o The request transaction object\r
207          * @param {Object} options The callback's <tt>options</tt> property as passed to the {@link #request} function\r
208          */\r
209         'load',\r
210         /**\r
211          * @event loadexception\r
212          * <p>This event is <b>deprecated</b>.  The signature of the loadexception event\r
213          * varies depending on the proxy, use the catch-all {@link #exception} event instead.\r
214          * This event will fire in addition to the {@link #exception} event.</p>\r
215          * @param {misc} misc See {@link #exception}.\r
216          * @deprecated\r
217          */\r
218         'loadexception',\r
219         /**\r
220          * @event beforewrite\r
221          * <p>Fires before a request is generated for one of the actions Ext.data.Api.actions.create|update|destroy</p>\r
222          * <p>In addition to being fired through the DataProxy instance that raised the event, this event is also fired\r
223          * through the Ext.data.DataProxy <i>class</i> to allow for centralized processing of beforewrite events from <b>all</b>\r
224          * DataProxies by attaching a listener to the Ext.data.Proxy class itself.</p>\r
225          * @param {DataProxy} this The proxy for the request\r
226          * @param {String} action [Ext.data.Api.actions.create|update|destroy]\r
227          * @param {Record/Array[Record]} rs The Record(s) to create|update|destroy.\r
228          * @param {Object} params The request <code>params</code> object.  Edit <code>params</code> to add parameters to the request.\r
229          */\r
230         'beforewrite',\r
231         /**\r
232          * @event write\r
233          * <p>Fires before the request-callback is called</p>\r
234          * <p>In addition to being fired through the DataProxy instance that raised the event, this event is also fired\r
235          * through the Ext.data.DataProxy <i>class</i> to allow for centralized processing of write events from <b>all</b>\r
236          * DataProxies by attaching a listener to the Ext.data.Proxy class itself.</p>\r
237          * @param {DataProxy} this The proxy that sent the request\r
238          * @param {String} action [Ext.data.Api.actions.create|upate|destroy]\r
239          * @param {Object} data The data object extracted from the server-response\r
240          * @param {Object} response The decoded response from server\r
241          * @param {Record/Record{}} rs The records from Store\r
242          * @param {Object} options The callback's <tt>options</tt> property as passed to the {@link #request} function\r
243          */\r
244         'write'\r
245     );\r
246     Ext.data.DataProxy.superclass.constructor.call(this);\r
247 \r
248     // Prepare the proxy api.  Ensures all API-actions are defined with the Object-form.\r
249     try {\r
250         Ext.data.Api.prepare(this);\r
251     } catch (e) {\r
252         if (e instanceof Ext.data.Api.Error) {\r
253             e.toConsole();\r
254         }\r
255     }\r
256     // relay each proxy's events onto Ext.data.DataProxy class for centralized Proxy-listening\r
257     Ext.data.DataProxy.relayEvents(this, ['beforewrite', 'write', 'exception']);\r
258 };\r
259 \r
260 Ext.extend(Ext.data.DataProxy, Ext.util.Observable, {\r
261     /**\r
262      * @cfg {Boolean} restful\r
263      * <p>Defaults to <tt>false</tt>.  Set to <tt>true</tt> to operate in a RESTful manner.</p>\r
264      * <br><p> Note: this parameter will automatically be set to <tt>true</tt> if the\r
265      * {@link Ext.data.Store} it is plugged into is set to <code>restful: true</code>. If the\r
266      * Store is RESTful, there is no need to set this option on the proxy.</p>\r
267      * <br><p>RESTful implementations enable the serverside framework to automatically route\r
268      * actions sent to one url based upon the HTTP method, for example:\r
269      * <pre><code>\r
270 store: new Ext.data.Store({\r
271     restful: true,\r
272     proxy: new Ext.data.HttpProxy({url:'/users'}); // all requests sent to /users\r
273     ...\r
274 )}\r
275      * </code></pre>\r
276      * If there is no <code>{@link #api}</code> specified in the configuration of the proxy,\r
277      * all requests will be marshalled to a single RESTful url (/users) so the serverside\r
278      * framework can inspect the HTTP Method and act accordingly:\r
279      * <pre>\r
280 <u>Method</u>   <u>url</u>        <u>action</u>\r
281 POST     /users     create\r
282 GET      /users     read\r
283 PUT      /users/23  update\r
284 DESTROY  /users/23  delete\r
285      * </pre></p>\r
286      * <p>If set to <tt>true</tt>, a {@link Ext.data.Record#phantom non-phantom} record's\r
287      * {@link Ext.data.Record#id id} will be appended to the url. Some MVC (e.g., Ruby on Rails,\r
288      * Merb and Django) support segment based urls where the segments in the URL follow the\r
289      * Model-View-Controller approach:<pre><code>\r
290      * someSite.com/controller/action/id\r
291      * </code></pre>\r
292      * Where the segments in the url are typically:<div class="mdetail-params"><ul>\r
293      * <li>The first segment : represents the controller class that should be invoked.</li>\r
294      * <li>The second segment : represents the class function, or method, that should be called.</li>\r
295      * <li>The third segment : represents the ID (a variable typically passed to the method).</li>\r
296      * </ul></div></p>\r
297      * <br><p>Refer to <code>{@link Ext.data.DataProxy#api}</code> for additional information.</p>\r
298      */\r
299     restful: false,\r
300 \r
301     /**\r
302      * <p>Redefines the Proxy's API or a single action of an API. Can be called with two method signatures.</p>\r
303      * <p>If called with an object as the only parameter, the object should redefine the <b>entire</b> API, e.g.:</p><pre><code>\r
304 proxy.setApi({\r
305     read    : '/users/read',\r
306     create  : '/users/create',\r
307     update  : '/users/update',\r
308     destroy : '/users/destroy'\r
309 });\r
310 </code></pre>\r
311      * <p>If called with two parameters, the first parameter should be a string specifying the API action to\r
312      * redefine and the second parameter should be the URL (or function if using DirectProxy) to call for that action, e.g.:</p><pre><code>\r
313 proxy.setApi(Ext.data.Api.actions.read, '/users/new_load_url');\r
314 </code></pre>\r
315      * @param {String/Object} api An API specification object, or the name of an action.\r
316      * @param {String/Function} url The URL (or function if using DirectProxy) to call for the action.\r
317      */\r
318     setApi : function() {\r
319         if (arguments.length == 1) {\r
320             var valid = Ext.data.Api.isValid(arguments[0]);\r
321             if (valid === true) {\r
322                 this.api = arguments[0];\r
323             }\r
324             else {\r
325                 throw new Ext.data.Api.Error('invalid', valid);\r
326             }\r
327         }\r
328         else if (arguments.length == 2) {\r
329             if (!Ext.data.Api.isAction(arguments[0])) {\r
330                 throw new Ext.data.Api.Error('invalid', arguments[0]);\r
331             }\r
332             this.api[arguments[0]] = arguments[1];\r
333         }\r
334         Ext.data.Api.prepare(this);\r
335     },\r
336 \r
337     /**\r
338      * Returns true if the specified action is defined as a unique action in the api-config.\r
339      * request.  If all API-actions are routed to unique urls, the xaction parameter is unecessary.  However, if no api is defined\r
340      * and all Proxy actions are routed to DataProxy#url, the server-side will require the xaction parameter to perform a switch to\r
341      * the corresponding code for CRUD action.\r
342      * @param {String [Ext.data.Api.CREATE|READ|UPDATE|DESTROY]} action\r
343      * @return {Boolean}\r
344      */\r
345     isApiAction : function(action) {\r
346         return (this.api[action]) ? true : false;\r
347     },\r
348 \r
349     /**\r
350      * All proxy actions are executed through this method.  Automatically fires the "before" + action event\r
351      * @param {String} action Name of the action\r
352      * @param {Ext.data.Record/Ext.data.Record[]/null} rs Will be null when action is 'load'\r
353      * @param {Object} params\r
354      * @param {Ext.data.DataReader} reader\r
355      * @param {Function} callback\r
356      * @param {Object} scope Scope with which to call the callback (defaults to the Proxy object)\r
357      * @param {Object} options Any options specified for the action (e.g. see {@link Ext.data.Store#load}.\r
358      */\r
359     request : function(action, rs, params, reader, callback, scope, options) {\r
360         if (!this.api[action] && !this.load) {\r
361             throw new Ext.data.DataProxy.Error('action-undefined', action);\r
362         }\r
363         params = params || {};\r
364         if ((action === Ext.data.Api.actions.read) ? this.fireEvent("beforeload", this, params) : this.fireEvent("beforewrite", this, action, rs, params) !== false) {\r
365             this.doRequest.apply(this, arguments);\r
366         }\r
367         else {\r
368             callback.call(scope || this, null, options, false);\r
369         }\r
370     },\r
371 \r
372 \r
373     /**\r
374      * <b>Deprecated</b> load method using old method signature. See {@doRequest} for preferred method.\r
375      * @deprecated\r
376      * @param {Object} params\r
377      * @param {Object} reader\r
378      * @param {Object} callback\r
379      * @param {Object} scope\r
380      * @param {Object} arg\r
381      */\r
382     load : null,\r
383 \r
384     /**\r
385      * @cfg {Function} doRequest Abstract method that should be implemented in all subclasses\r
386      * (e.g.: {@link Ext.data.HttpProxy#doRequest HttpProxy.doRequest},\r
387      * {@link Ext.data.DirectProxy#doRequest DirectProxy.doRequest}).\r
388      */\r
389     doRequest : function(action, rs, params, reader, callback, scope, options) {\r
390         // default implementation of doRequest for backwards compatibility with 2.0 proxies.\r
391         // If we're executing here, the action is probably "load".\r
392         // Call with the pre-3.0 method signature.\r
393         this.load(params, reader, callback, scope, options);\r
394     },\r
395 \r
396     /**\r
397      * buildUrl\r
398      * Sets the appropriate url based upon the action being executed.  If restful is true, and only a single record is being acted upon,\r
399      * url will be built Rails-style, as in "/controller/action/32".  restful will aply iff the supplied record is an\r
400      * instance of Ext.data.Record rather than an Array of them.\r
401      * @param {String} action The api action being executed [read|create|update|destroy]\r
402      * @param {Ext.data.Record/Array[Ext.data.Record]} The record or Array of Records being acted upon.\r
403      * @return {String} url\r
404      * @private\r
405      */\r
406     buildUrl : function(action, record) {\r
407         record = record || null;\r
408         var url = (this.api[action]) ? this.api[action].url : this.url;\r
409         if (!url) {\r
410             throw new Ext.data.Api.Error('invalid-url', action);\r
411         }\r
412 \r
413         // look for urls having "provides" suffix (from Rails/Merb and others...),\r
414         // e.g.: /users.json, /users.xml, etc\r
415         // with restful routes, we need urls like:\r
416         // PUT /users/1.json\r
417         // DELETE /users/1.json\r
418         var format = null;\r
419         var m = url.match(/(.*)(\.json|\.xml|\.html)$/);\r
420         if (m) {\r
421             format = m[2];  // eg ".json"\r
422             url = m[1];     // eg: "/users"\r
423         }\r
424         // prettyUrls is deprectated in favor of restful-config\r
425         if ((this.prettyUrls === true || this.restful === true) && record instanceof Ext.data.Record && !record.phantom) {\r
426             url += '/' + record.id;\r
427         }\r
428         if (format) {   // <-- append the request format if exists (ie: /users/update/69[.json])\r
429             url += format;\r
430         }\r
431         return url;\r
432     },\r
433 \r
434     /**\r
435      * Destroys the proxy by purging any event listeners and cancelling any active requests.\r
436      */\r
437     destroy: function(){\r
438         this.purgeListeners();\r
439     }\r
440 });\r
441 \r
442 // Apply the Observable prototype to the DataProxy class so that proxy instances can relay their\r
443 // events to the class.  Allows for centralized listening of all proxy instances upon the DataProxy class.\r
444 Ext.apply(Ext.data.DataProxy, Ext.util.Observable.prototype);\r
445 Ext.util.Observable.call(Ext.data.DataProxy);\r
446 \r
447 /**\r
448  * @class Ext.data.DataProxy.Error\r
449  * @extends Ext.Error\r
450  * DataProxy Error extension.\r
451  * constructor\r
452  * @param {String} name\r
453  * @param {Record/Array[Record]/Array}\r
454  */\r
455 Ext.data.DataProxy.Error = Ext.extend(Ext.Error, {\r
456     constructor : function(message, arg) {\r
457         this.arg = arg;\r
458         Ext.Error.call(this, message);\r
459     },\r
460     name: 'Ext.data.DataProxy'\r
461 });\r
462 Ext.apply(Ext.data.DataProxy.Error.prototype, {\r
463     lang: {\r
464         'action-undefined': "DataProxy attempted to execute an API-action but found an undefined url / function.  Please review your Proxy url/api-configuration.",\r
465         'api-invalid': 'Recieved an invalid API-configuration.  Please ensure your proxy API-configuration contains only the actions from Ext.data.Api.actions.'\r
466     }\r
467 });\r
468 \r
469 \r