Upgrade to ExtJS 3.0.0 - Released 07/06/2009
[extjs.git] / src / data / DataProxy.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.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>If the specific URL for a given CRUD action is undefined, the CRUD action request\r
72      * will be directed to the configured <tt>{@link Ext.data.Connection#url url}</tt>.</p>\r
73      * <br><p><b>Note</b>: To modify the URL for an action dynamically the appropriate API\r
74      * property should be modified before the action is requested using the corresponding before\r
75      * action event.  For example to modify the URL associated with the load action:\r
76      * <pre><code>\r
77 // modify the url for the action\r
78 myStore.on({\r
79     beforeload: {\r
80         fn: function (store, options) {\r
81             // use <tt>{@link Ext.data.HttpProxy#setUrl setUrl}</tt> to change the URL for *just* this request.\r
82             store.proxy.setUrl('changed1.php');\r
83 \r
84             // set optional second parameter to true to make this URL change\r
85             // permanent, applying this URL for all subsequent requests.\r
86             store.proxy.setUrl('changed1.php', true);\r
87 \r
88             // manually set the <b>private</b> connection URL.\r
89             // <b>Warning:</b>  Accessing the private URL property should be avoided.\r
90             // Use the public method <tt>{@link Ext.data.HttpProxy#setUrl setUrl}</tt> instead, shown above.\r
91             // It should be noted that changing the URL like this will affect\r
92             // the URL for just this request.  Subsequent requests will use the\r
93             // API or URL defined in your initial proxy configuration.\r
94             store.proxy.conn.url = 'changed1.php';\r
95 \r
96             // proxy URL will be superseded by API (only if proxy created to use ajax):\r
97             // It should be noted that proxy API changes are permanent and will\r
98             // be used for all subsequent requests.\r
99             store.proxy.api.load = 'changed2.php';\r
100 \r
101             // However, altering the proxy API should be done using the public\r
102             // method <tt>{@link Ext.data.DataProxy#setApi setApi}</tt> instead.\r
103             store.proxy.setApi('load', 'changed2.php');\r
104 \r
105             // Or set the entire API with a config-object.\r
106             // When using the config-object option, you must redefine the <b>entire</b>\r
107             // API -- not just a specific action of it.\r
108             store.proxy.setApi({\r
109                 read    : 'changed_read.php',\r
110                 create  : 'changed_create.php',\r
111                 update  : 'changed_update.php',\r
112                 destroy : 'changed_destroy.php'\r
113             });\r
114         }\r
115     }\r
116 });\r
117      * </code></pre>\r
118      * </p>\r
119      */\r
120     // Prepare the proxy api.  Ensures all API-actions are defined with the Object-form.\r
121     try {\r
122         Ext.data.Api.prepare(this);\r
123     } catch (e) {\r
124         if (e instanceof Ext.data.Api.Error) {\r
125             e.toConsole();\r
126         }\r
127     }\r
128 \r
129     this.addEvents(\r
130         /**\r
131          * @event exception\r
132          * <p>Fires if an exception occurs in the Proxy during a remote request.\r
133          * This event is relayed through a corresponding\r
134          * {@link Ext.data.Store}.{@link Ext.data.Store#exception exception},\r
135          * so any Store instance may observe this event.\r
136          * This event can be fired for one of two reasons:</p>\r
137          * <div class="mdetail-params"><ul>\r
138          * <li>remote-request <b>failed</b> : <div class="sub-desc">\r
139          * The server did not return status === 200.\r
140          * </div></li>\r
141          * <li>remote-request <b>succeeded</b> : <div class="sub-desc">\r
142          * The remote-request succeeded but the reader could not read the response.\r
143          * This means the server returned data, but the configured Reader threw an\r
144          * error while reading the response.  In this case, this event will be\r
145          * raised and the caught error will be passed along into this event.\r
146          * </div></li>\r
147          * </ul></div>\r
148          * <br><p>This event fires with two different contexts based upon the 2nd\r
149          * parameter <tt>type [remote|response]</tt>.  The first four parameters\r
150          * are identical between the two contexts -- only the final two parameters\r
151          * differ.</p>\r
152          * @param {DataProxy} this The proxy that sent the request\r
153          * @param {String} type\r
154          * <p>The value of this parameter will be either <tt>'response'</tt> or <tt>'remote'</tt>.</p>\r
155          * <div class="mdetail-params"><ul>\r
156          * <li><b><tt>'response'</tt></b> : <div class="sub-desc">\r
157          * <p>An <b>invalid</b> response from the server was returned: either 404,\r
158          * 500 or the response meta-data does not match that defined in the DataReader\r
159          * (e.g.: root, idProperty, successProperty).</p>\r
160          * </div></li>\r
161          * <li><b><tt>'remote'</tt></b> : <div class="sub-desc">\r
162          * <p>A <b>valid</b> response was returned from the server having\r
163          * successProperty === false.  This response might contain an error-message\r
164          * sent from the server.  For example, the user may have failed\r
165          * authentication/authorization or a database validation error occurred.</p>\r
166          * </div></li>\r
167          * </ul></div>\r
168          * @param {String} action Name of the action (see {@link Ext.data.Api#actions}.\r
169          * @param {Object} options The options for the action that were specified in the {@link #request}.\r
170          * @param {Object} response\r
171          * <p>The value of this parameter depends on the value of the <code>type</code> parameter:</p>\r
172          * <div class="mdetail-params"><ul>\r
173          * <li><b><tt>'response'</tt></b> : <div class="sub-desc">\r
174          * <p>The raw browser response object (e.g.: XMLHttpRequest)</p>\r
175          * </div></li>\r
176          * <li><b><tt>'remote'</tt></b> : <div class="sub-desc">\r
177          * <p>The decoded response object sent from the server.</p>\r
178          * </div></li>\r
179          * </ul></div>\r
180          * @param {Mixed} arg\r
181          * <p>The type and value of this parameter depends on the value of the <code>type</code> parameter:</p>\r
182          * <div class="mdetail-params"><ul>\r
183          * <li><b><tt>'response'</tt></b> : Error<div class="sub-desc">\r
184          * <p>The JavaScript Error object caught if the configured Reader could not read the data.\r
185          * If the remote request returns success===false, this parameter will be null.</p>\r
186          * </div></li>\r
187          * <li><b><tt>'remote'</tt></b> : Record/Record[]<div class="sub-desc">\r
188          * <p>This parameter will only exist if the <tt>action</tt> was a <b>write</b> action\r
189          * (Ext.data.Api.actions.create|update|destroy).</p>\r
190          * </div></li>\r
191          * </ul></div>\r
192          */\r
193         'exception',\r
194         /**\r
195          * @event beforeload\r
196          * Fires before a request to retrieve a data object.\r
197          * @param {DataProxy} this The proxy for the request\r
198          * @param {Object} params The params object passed to the {@link #request} function\r
199          */\r
200         'beforeload',\r
201         /**\r
202          * @event load\r
203          * Fires before the load method's callback is called.\r
204          * @param {DataProxy} this The proxy for the request\r
205          * @param {Object} o The request transaction object\r
206          * @param {Object} options The callback's <tt>options</tt> property as passed to the {@link #request} function\r
207          */\r
208         'load',\r
209         /**\r
210          * @event loadexception\r
211          * <p>This event is <b>deprecated</b>.  The signature of the loadexception event\r
212          * varies depending on the proxy, use the catch-all {@link #exception} event instead.\r
213          * This event will fire in addition to the {@link #exception} event.</p>\r
214          * @param {misc} misc See {@link #exception}.\r
215          * @deprecated\r
216          */\r
217         'loadexception',\r
218         /**\r
219          * @event beforewrite\r
220          * Fires before a request is generated for one of the actions Ext.data.Api.actions.create|update|destroy\r
221          * @param {DataProxy} this The proxy for the request\r
222          * @param {String} action [Ext.data.Api.actions.create|update|destroy]\r
223          * @param {Record/Array[Record]} rs The Record(s) to create|update|destroy.\r
224          * @param {Object} params The request <code>params</code> object.  Edit <code>params</code> to add parameters to the request.\r
225          */\r
226         'beforewrite',\r
227         /**\r
228          * @event write\r
229          * Fires before the request-callback is called\r
230          * @param {DataProxy} this The proxy that sent the request\r
231          * @param {String} action [Ext.data.Api.actions.create|upate|destroy]\r
232          * @param {Object} data The data object extracted from the server-response\r
233          * @param {Object} response The decoded response from server\r
234          * @param {Record/Record{}} rs The records from Store\r
235          * @param {Object} options The callback's <tt>options</tt> property as passed to the {@link #request} function\r
236          */\r
237         'write'\r
238     );\r
239     Ext.data.DataProxy.superclass.constructor.call(this);\r
240 };\r
241 \r
242 Ext.extend(Ext.data.DataProxy, Ext.util.Observable, {\r
243     /**\r
244      * @cfg {Boolean} restful\r
245      * <p>Defaults to <tt>false</tt>.  Set to <tt>true</tt> to operate in a RESTful manner.</p>\r
246      * <br><p> Note: this parameter will automatically be set to <tt>true</tt> if the\r
247      * {@link Ext.data.Store} it is plugged into is set to <code>restful: true</code>. If the\r
248      * Store is RESTful, there is no need to set this option on the proxy.</p>\r
249      * <br><p>RESTful implementations enable the serverside framework to automatically route\r
250      * actions sent to one url based upon the HTTP method, for example:\r
251      * <pre><code>\r
252 store: new Ext.data.Store({\r
253     restful: true,\r
254     proxy: new Ext.data.HttpProxy({url:'/users'}); // all requests sent to /users\r
255     ...\r
256 )}\r
257      * </code></pre>\r
258      * There is no <code>{@link #api}</code> specified in the configuration of the proxy,\r
259      * all requests will be marshalled to a single RESTful url (/users) so the serverside\r
260      * framework can inspect the HTTP Method and act accordingly:\r
261      * <pre>\r
262 <u>Method</u>   <u>url</u>        <u>action</u>\r
263 POST     /users     create\r
264 GET      /users     read\r
265 PUT      /users/23  update\r
266 DESTROY  /users/23  delete\r
267      * </pre></p>\r
268      */\r
269     restful: false,\r
270 \r
271     /**\r
272      * <p>Redefines the Proxy's API or a single action of an API. Can be called with two method signatures.</p>\r
273      * <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
274 proxy.setApi({\r
275     read    : '/users/read',\r
276     create  : '/users/create',\r
277     update  : '/users/update',\r
278     destroy : '/users/destroy'\r
279 });\r
280 </code></pre>\r
281      * <p>If called with two parameters, the first parameter should be a string specifying the API action to\r
282      * 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
283 proxy.setApi(Ext.data.Api.actions.read, '/users/new_load_url');\r
284 </code></pre>\r
285      * @param {String/Object} api An API specification object, or the name of an action.\r
286      * @param {String/Function} url The URL (or function if using DirectProxy) to call for the action.\r
287      */\r
288     setApi : function() {\r
289         if (arguments.length == 1) {\r
290             var valid = Ext.data.Api.isValid(arguments[0]);\r
291             if (valid === true) {\r
292                 this.api = arguments[0];\r
293             }\r
294             else {\r
295                 throw new Ext.data.Api.Error('invalid', valid);\r
296             }\r
297         }\r
298         else if (arguments.length == 2) {\r
299             if (!Ext.data.Api.isAction(arguments[0])) {\r
300                 throw new Ext.data.Api.Error('invalid', arguments[0]);\r
301             }\r
302             this.api[arguments[0]] = arguments[1];\r
303         }\r
304         Ext.data.Api.prepare(this);\r
305     },\r
306 \r
307     /**\r
308      * Returns true if the specified action is defined as a unique action in the api-config.\r
309      * request.  If all API-actions are routed to unique urls, the xaction parameter is unecessary.  However, if no api is defined\r
310      * and all Proxy actions are routed to DataProxy#url, the server-side will require the xaction parameter to perform a switch to\r
311      * the corresponding code for CRUD action.\r
312      * @param {String [Ext.data.Api.CREATE|READ|UPDATE|DESTROY]} action\r
313      * @return {Boolean}\r
314      */\r
315     isApiAction : function(action) {\r
316         return (this.api[action]) ? true : false;\r
317     },\r
318 \r
319     /**\r
320      * All proxy actions are executed through this method.  Automatically fires the "before" + action event\r
321      * @param {String} action Name of the action\r
322      * @param {Ext.data.Record/Ext.data.Record[]/null} rs Will be null when action is 'load'\r
323      * @param {Object} params\r
324      * @param {Ext.data.DataReader} reader\r
325      * @param {Function} callback\r
326      * @param {Object} scope Scope with which to call the callback (defaults to the Proxy object)\r
327      * @param {Object} options Any options specified for the action (e.g. see {@link Ext.data.Store#load}.\r
328      */\r
329     request : function(action, rs, params, reader, callback, scope, options) {\r
330         if (!this.api[action] && !this.load) {\r
331             throw new Ext.data.DataProxy.Error('action-undefined', action);\r
332         }\r
333         params = params || {};\r
334         if ((action === Ext.data.Api.actions.read) ? this.fireEvent("beforeload", this, params) : this.fireEvent("beforewrite", this, action, rs, params) !== false) {\r
335             this.doRequest.apply(this, arguments);\r
336         }\r
337         else {\r
338             callback.call(scope || this, null, options, false);\r
339         }\r
340     },\r
341 \r
342 \r
343     /**\r
344      * <b>Deprecated</b> load method using old method signature. See {@doRequest} for preferred method.\r
345      * @deprecated\r
346      * @param {Object} params\r
347      * @param {Object} reader\r
348      * @param {Object} callback\r
349      * @param {Object} scope\r
350      * @param {Object} arg\r
351      */\r
352     load : null,\r
353 \r
354     /**\r
355      * @cfg {Function} doRequest Abstract method that should be implemented in all subclasses\r
356      * (e.g.: {@link Ext.data.HttpProxy#doRequest HttpProxy.doRequest},\r
357      * {@link Ext.data.DirectProxy#doRequest DirectProxy.doRequest}).\r
358      */\r
359     doRequest : function(action, rs, params, reader, callback, scope, options) {\r
360         // default implementation of doRequest for backwards compatibility with 2.0 proxies.\r
361         // If we're executing here, the action is probably "load".\r
362         // Call with the pre-3.0 method signature.\r
363         this.load(params, reader, callback, scope, options);\r
364     },\r
365 \r
366     /**\r
367      * buildUrl\r
368      * Sets the appropriate url based upon the action being executed.  If restful is true, and only a single record is being acted upon,\r
369      * url will be built Rails-style, as in "/controller/action/32".  restful will aply iff the supplied record is an\r
370      * instance of Ext.data.Record rather than an Array of them.\r
371      * @param {String} action The api action being executed [read|create|update|destroy]\r
372      * @param {Ext.data.Record/Array[Ext.data.Record]} The record or Array of Records being acted upon.\r
373      * @return {String} url\r
374      * @private\r
375      */\r
376     buildUrl : function(action, record) {\r
377         record = record || null;\r
378         var url = (this.api[action]) ? this.api[action].url : this.url;\r
379         if (!url) {\r
380             throw new Ext.data.Api.Error('invalid-url', action);\r
381         }\r
382 \r
383         var format = null;\r
384         var m = url.match(/(.*)(\.\w+)$/);  // <-- look for urls with "provides" suffix, e.g.: /users.json, /users.xml, etc\r
385         if (m) {\r
386             format = m[2];\r
387             url = m[1];\r
388         }\r
389         // prettyUrls is deprectated in favor of restful-config\r
390         if ((this.prettyUrls === true || this.restful === true) && record instanceof Ext.data.Record && !record.phantom) {\r
391             url += '/' + record.id;\r
392         }\r
393         if (format) {   // <-- append the request format if exists (ie: /users/update/69[.json])\r
394             url += format;\r
395         }\r
396         return url;\r
397     },\r
398 \r
399     /**\r
400      * Destroys the proxy by purging any event listeners and cancelling any active requests.\r
401      */\r
402     destroy: function(){\r
403         this.purgeListeners();\r
404     }\r
405 });\r
406 \r
407 /**\r
408  * @class Ext.data.DataProxy.Error\r
409  * @extends Ext.Error\r
410  * DataProxy Error extension.\r
411  * constructor\r
412  * @param {String} name\r
413  * @param {Record/Array[Record]/Array}\r
414  */\r
415 Ext.data.DataProxy.Error = Ext.extend(Ext.Error, {\r
416     constructor : function(message, arg) {\r
417         this.arg = arg;\r
418         Ext.Error.call(this, message);\r
419     },\r
420     name: 'Ext.data.DataProxy'\r
421 });\r
422 Ext.apply(Ext.data.DataProxy.Error.prototype, {\r
423     lang: {\r
424         'action-undefined': "DataProxy attempted to execute an API-action but found an undefined url / function.  Please review your Proxy url/api-configuration.",\r
425         'api-invalid': 'Recieved an invalid API-configuration.  Please ensure your proxy API-configuration contains only the actions from Ext.data.Api.actions.'\r
426     }\r
427 });\r