PageRenderTime 21ms CodeModel.GetById 8ms app.highlight 7ms RepoModel.GetById 1ms app.codeStats 0ms

/hippo/src/main/webapp/ext/src/data/DataProxy.js

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