0
# RESTful Resources
1
2
Resource abstraction for RESTful APIs providing predefined CRUD operations with URL templating, parameter binding, and customizable actions.
3
4
## Capabilities
5
6
### Resource Creation
7
8
Create a resource object with predefined methods for common RESTful operations.
9
10
```javascript { .api }
11
/**
12
* Create a RESTful resource with predefined actions
13
* @param url - URL template with optional parameters (e.g., '/users{/id}')
14
* @param params - Default parameters for URL substitution
15
* @param actions - Custom actions to extend default resource methods
16
* @param options - Default HTTP options for all resource methods
17
* @returns Resource object with CRUD methods
18
*/
19
function $resource(
20
url: string,
21
params?: object,
22
actions?: object,
23
options?: HttpOptions
24
): ResourceMethods;
25
26
interface ResourceMethods {
27
get: ResourceMethod;
28
save: ResourceMethod;
29
query: ResourceMethod;
30
update: ResourceMethod;
31
remove: ResourceMethod;
32
delete: ResourceMethod;
33
}
34
35
interface ResourceMethod {
36
(params?: any, data?: any): Promise<HttpResponse>;
37
(params?: any): Promise<HttpResponse>;
38
(): Promise<HttpResponse>;
39
}
40
```
41
42
**Usage Examples:**
43
44
```javascript
45
// Basic resource
46
const UserResource = this.$resource('/api/users{/id}');
47
48
// Resource with default parameters
49
const UserResource = this.$resource('/api/users{/id}', {id: '@id'});
50
51
// Resource with custom actions
52
const UserResource = this.$resource('/api/users{/id}', {}, {
53
activate: {method: 'POST', url: '/api/users{/id}/activate'},
54
search: {method: 'GET', url: '/api/users/search'}
55
});
56
57
// Resource with default options
58
const UserResource = this.$resource('/api/users{/id}', {}, {}, {
59
headers: {'Authorization': 'Bearer token'}
60
});
61
```
62
63
### Default Resource Actions
64
65
All resources come with six predefined actions for common CRUD operations.
66
67
```javascript { .api }
68
// Default actions available on all resources
69
const defaultActions = {
70
get: { method: 'GET' },
71
save: { method: 'POST' },
72
query: { method: 'GET' },
73
update: { method: 'PUT' },
74
remove: { method: 'DELETE' },
75
delete: { method: 'DELETE' }
76
};
77
```
78
79
**Usage Examples:**
80
81
```javascript
82
const UserResource = this.$resource('/api/users{/id}');
83
84
// GET /api/users/1
85
UserResource.get({id: 1}).then(response => {
86
console.log('User:', response.body);
87
});
88
89
// GET /api/users (query for multiple)
90
UserResource.query().then(response => {
91
console.log('All users:', response.body);
92
});
93
94
// POST /api/users (create new)
95
UserResource.save({name: 'John', email: 'john@example.com'}).then(response => {
96
console.log('Created user:', response.body);
97
});
98
99
// POST /api/users (create with params and data)
100
UserResource.save({}, {name: 'John', email: 'john@example.com'}).then(response => {
101
console.log('Created user:', response.body);
102
});
103
104
// PUT /api/users/1 (update existing)
105
UserResource.update({id: 1}, {name: 'John Updated'}).then(response => {
106
console.log('Updated user:', response.body);
107
});
108
109
// DELETE /api/users/1
110
UserResource.remove({id: 1}).then(response => {
111
console.log('User deleted');
112
});
113
114
// DELETE /api/users/1 (alias for remove)
115
UserResource.delete({id: 1}).then(response => {
116
console.log('User deleted');
117
});
118
```
119
120
### URL Templates
121
122
Resources support URI templates for dynamic URL construction with parameter substitution.
123
124
**Usage Examples:**
125
126
```javascript
127
// Simple parameter substitution
128
const UserResource = this.$resource('/api/users/{id}');
129
UserResource.get({id: 123}); // GET /api/users/123
130
131
// Optional parameters with braces
132
const UserResource = this.$resource('/api/users{/id}');
133
UserResource.query(); // GET /api/users
134
UserResource.get({id: 123}); // GET /api/users/123
135
136
// Multiple parameters
137
const PostResource = this.$resource('/api/users/{userId}/posts{/postId}');
138
PostResource.query({userId: 1}); // GET /api/users/1/posts
139
PostResource.get({userId: 1, postId: 5}); // GET /api/users/1/posts/5
140
141
// Default parameters with @ prefix (extracts from data)
142
const UserResource = this.$resource('/api/users/{id}', {id: '@id'});
143
UserResource.update({id: 1, name: 'John'}); // PUT /api/users/1
144
```
145
146
### Custom Actions
147
148
Extend resources with custom actions for specialized endpoints.
149
150
```javascript { .api }
151
interface ResourceAction {
152
method: string;
153
url?: string;
154
params?: object;
155
headers?: object;
156
[key: string]: any;
157
}
158
```
159
160
**Usage Examples:**
161
162
```javascript
163
// Resource with custom actions
164
const UserResource = this.$resource('/api/users{/id}', {}, {
165
// Custom action with different URL
166
activate: {
167
method: 'POST',
168
url: '/api/users{/id}/activate'
169
},
170
171
// Custom action with different method
172
search: {
173
method: 'GET',
174
url: '/api/users/search'
175
},
176
177
// Custom action with additional parameters
178
resetPassword: {
179
method: 'POST',
180
url: '/api/users{/id}/reset-password',
181
params: {sendEmail: true}
182
}
183
});
184
185
// Use custom actions
186
UserResource.activate({id: 1}).then(response => {
187
console.log('User activated');
188
});
189
190
UserResource.search({q: 'john'}).then(response => {
191
console.log('Search results:', response.body);
192
});
193
194
UserResource.resetPassword({id: 1}).then(response => {
195
console.log('Password reset initiated');
196
});
197
```
198
199
### Parameter Binding
200
201
Resources support flexible parameter binding for URL construction and data extraction.
202
203
**Usage Examples:**
204
205
```javascript
206
// Default parameter extraction from data
207
const UserResource = this.$resource('/api/users/{id}', {id: '@id'});
208
209
// When calling save/update, id is extracted from data object
210
const userData = {id: 1, name: 'John', email: 'john@example.com'};
211
UserResource.update(userData); // PUT /api/users/1
212
213
// Explicit parameters override extracted values
214
UserResource.update({id: 2}, userData); // PUT /api/users/2
215
216
// Complex parameter extraction
217
const PostResource = this.$resource('/api/users/{userId}/posts/{id}', {
218
userId: '@author.id',
219
id: '@id'
220
});
221
222
const postData = {
223
id: 5,
224
title: 'My Post',
225
author: {id: 1, name: 'John'}
226
};
227
PostResource.update(postData); // PUT /api/users/1/posts/5
228
```
229
230
### Error Handling
231
232
Resource methods return promises that can be handled with standard promise patterns.
233
234
**Usage Examples:**
235
236
```javascript
237
const UserResource = this.$resource('/api/users{/id}');
238
239
// Promise-based error handling
240
UserResource.get({id: 999}).then(response => {
241
console.log('User found:', response.body);
242
}, response => {
243
if (response.status === 404) {
244
console.log('User not found');
245
} else {
246
console.error('Error:', response.status, response.statusText);
247
}
248
});
249
250
// Async/await error handling
251
async function getUser(id) {
252
try {
253
const response = await UserResource.get({id});
254
return response.body;
255
} catch (response) {
256
if (response.status === 404) {
257
return null;
258
}
259
throw new Error(`Failed to get user: ${response.statusText}`);
260
}
261
}
262
```
263
264
### Global Resource Configuration
265
266
Configure default behavior for all resources.
267
268
```javascript { .api }
269
// Default resource actions (can be overridden)
270
Vue.resource.actions = {
271
get: { method: 'GET' },
272
save: { method: 'POST' },
273
query: { method: 'GET' },
274
update: { method: 'PUT' },
275
remove: { method: 'DELETE' },
276
delete: { method: 'DELETE' }
277
};
278
```
279
280
**Usage Examples:**
281
282
```javascript
283
// Add a custom action to all resources
284
Vue.resource.actions.patch = {method: 'PATCH'};
285
286
// Now all resources have a patch method
287
const UserResource = this.$resource('/api/users{/id}');
288
UserResource.patch({id: 1}, {name: 'Updated Name'});
289
```
290
291
## Types
292
293
```javascript { .api }
294
interface ResourceMethods {
295
/** Get a single resource by ID */
296
get: ResourceMethod;
297
/** Create a new resource (POST) */
298
save: ResourceMethod;
299
/** Query for multiple resources (GET collection) */
300
query: ResourceMethod;
301
/** Update an existing resource (PUT) */
302
update: ResourceMethod;
303
/** Delete a resource */
304
remove: ResourceMethod;
305
/** Delete a resource (alias for remove) */
306
delete: ResourceMethod;
307
}
308
309
interface ResourceMethod {
310
/** Call with parameters and data */
311
(params: any, data?: any): Promise<HttpResponse>;
312
/** Call with parameters only */
313
(params: any): Promise<HttpResponse>;
314
/** Call without parameters */
315
(): Promise<HttpResponse>;
316
}
317
318
interface ResourceAction {
319
/** HTTP method for the action */
320
method: string;
321
/** URL template for the action (optional, uses resource URL if not specified) */
322
url?: string;
323
/** Default parameters for the action */
324
params?: object;
325
/** Default headers for the action */
326
headers?: object;
327
/** Additional action configuration */
328
[key: string]: any;
329
}
330
331
interface ResourceActions {
332
get: ResourceAction;
333
save: ResourceAction;
334
query: ResourceAction;
335
update: ResourceAction;
336
remove: ResourceAction;
337
delete: ResourceAction;
338
}
339
```