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