Upgrade to ExtJS 4.0.0 - Released 04/26/2011
[extjs.git] / src / data / proxy / Rest.js
1 /**
2  * @author Ed Spencer
3  * @class Ext.data.proxy.Rest
4  * @extends Ext.data.proxy.Ajax
5  * 
6  * <p>RestProxy is a specialization of the {@link Ext.data.proxy.Ajax AjaxProxy} which simply maps the four actions 
7  * (create, read, update and destroy) to RESTful HTTP verbs. For example, let's set up a {@link Ext.data.Model Model}
8  * with an inline RestProxy</p>
9  * 
10 <pre><code>
11 Ext.define('User', {
12     extend: 'Ext.data.Model',
13     fields: ['id', 'name', 'email'],
14
15     proxy: {
16         type: 'rest',
17         url : '/users'
18     }
19 });
20 </code></pre>
21  * 
22  * <p>Now we can create a new User instance and save it via the RestProxy. Doing this will cause the Proxy to send a
23  * POST request to '/users':
24  * 
25 <pre><code>
26 var user = Ext.ModelManager.create({name: 'Ed Spencer', email: 'ed@sencha.com'}, 'User');
27
28 user.save(); //POST /users
29 </code></pre>
30  * 
31  * <p>Let's expand this a little and provide a callback for the {@link Ext.data.Model#save} call to update the Model
32  * once it has been created. We'll assume the creation went successfully and that the server gave this user an ID of 
33  * 123:</p>
34  * 
35 <pre><code>
36 user.save({
37     success: function(user) {
38         user.set('name', 'Khan Noonien Singh');
39
40         user.save(); //PUT /users/123
41     }
42 });
43 </code></pre>
44  * 
45  * <p>Now that we're no longer creating a new Model instance, the request method is changed to an HTTP PUT, targeting
46  * the relevant url for that user. Now let's delete this user, which will use the DELETE method:</p>
47  * 
48 <pre><code>
49     user.destroy(); //DELETE /users/123
50 </code></pre>
51  * 
52  * <p>Finally, when we perform a load of a Model or Store, RestProxy will use the GET method:</p>
53  * 
54 <pre><code>
55 //1. Load via Store
56
57 //the Store automatically picks up the Proxy from the User model
58 var store = new Ext.data.Store({
59     model: 'User'
60 });
61
62 store.load(); //GET /users
63
64 //2. Load directly from the Model
65
66 //GET /users/123
67 Ext.ModelManager.getModel('User').load(123, {
68     success: function(user) {
69         console.log(user.getId()); //outputs 123
70     }
71 });
72 </code></pre>
73  * 
74  * <p><u>Url generation</u></p>
75  * 
76  * <p>RestProxy is able to automatically generate the urls above based on two configuration options - {@link #appendId}
77  * and {@link #format}. If appendId is true (it is by default) then RestProxy will automatically append the ID of the 
78  * Model instance in question to the configured url, resulting in the '/users/123' that we saw above.</p>
79  * 
80  * <p>If the request is not for a specific Model instance (e.g. loading a Store), the url is not appended with an id. 
81  * RestProxy will automatically insert a '/' before the ID if one is not already present.</p>
82  * 
83 <pre><code>
84 new Ext.data.proxy.Rest({
85     url: '/users',
86     appendId: true //default
87 });
88
89 // Collection url: /users
90 // Instance url  : /users/123
91 </code></pre>
92  * 
93  * <p>RestProxy can also optionally append a format string to the end of any generated url:</p>
94  * 
95 <pre><code>
96 new Ext.data.proxy.Rest({
97     url: '/users',
98     format: 'json'
99 });
100
101 // Collection url: /users.json
102 // Instance url  : /users/123.json
103 </code></pre>
104  * 
105  * <p>If further customization is needed, simply implement the {@link #buildUrl} method and add your custom generated
106  * url onto the {@link Ext.data.Request Request} object that is passed to buildUrl. See 
107  * <a href="source/RestProxy.html#method-Ext.data.proxy.Rest-buildUrl">RestProxy's implementation</a> for an example of
108  * how to achieve this.</p>
109  * 
110  * <p>Note that RestProxy inherits from {@link Ext.data.proxy.Ajax AjaxProxy}, which already injects all of the sorter,
111  * filter, group and paging options into the generated url. See the {@link Ext.data.proxy.Ajax AjaxProxy docs} for more
112  * details.</p>
113  */
114 Ext.define('Ext.data.proxy.Rest', {
115     extend: 'Ext.data.proxy.Ajax',
116     alternateClassName: 'Ext.data.RestProxy',
117     alias : 'proxy.rest',
118     
119     /**
120      * @cfg {Boolean} appendId True to automatically append the ID of a Model instance when performing a request based
121      * on that single instance. See RestProxy intro docs for more details. Defaults to true.
122      */
123     appendId: true,
124     
125     /**
126      * @cfg {String} format Optional data format to send to the server when making any request (e.g. 'json'). See the
127      * RestProxy intro docs for full details. Defaults to undefined.
128      */
129     
130     /**
131      * @cfg {Boolean} batchActions True to batch actions of a particular type when synchronizing the store.
132      * Defaults to <tt>false</tt>.
133      */
134     batchActions: false,
135     
136     /**
137      * Specialized version of buildUrl that incorporates the {@link #appendId} and {@link #format} options into the
138      * generated url. Override this to provide further customizations, but remember to call the superclass buildUrl
139      * so that additional parameters like the cache buster string are appended
140      */
141     buildUrl: function(request) {
142         var me        = this,
143             operation = request.operation,
144             records   = operation.records || [],
145             record    = records[0],
146             format    = me.format,
147             url       = me.getUrl(request),
148             id        = record ? record.getId() : operation.id;
149         
150         if (me.appendId && id) {
151             if (!url.match(/\/$/)) {
152                 url += '/';
153             }
154             
155             url += id;
156         }
157         
158         if (format) {
159             if (!url.match(/\.$/)) {
160                 url += '.';
161             }
162             
163             url += format;
164         }
165         
166         request.url = url;
167         
168         return me.callParent(arguments);
169     }
170 }, function() {
171     Ext.apply(this.prototype, {
172         /**
173          * Mapping of action name to HTTP request method. These default to RESTful conventions for the 'create', 'read',
174          * 'update' and 'destroy' actions (which map to 'POST', 'GET', 'PUT' and 'DELETE' respectively). This object should
175          * not be changed except globally via {@link Ext#override Ext.override} - the {@link #getMethod} function can be overridden instead.
176          * @property actionMethods
177          * @type Object
178          */
179         actionMethods: {
180             create : 'POST',
181             read   : 'GET',
182             update : 'PUT',
183             destroy: 'DELETE'
184         }
185     });
186 });