UNPKG

8.66 kBMarkdownView Raw
1Rest.js
2=======
3
4Just enough client, as you need it. Make HTTP requests from a browser or Node.js applying the only the client features you need. Configure a client once, and share it safely throughout your application. Easily extend with interceptors that wrap the request and/or response, or MIME type converters for rich data formats.
5
6
7Build Status
8------------
9
10<table>
11 <tr><td>Master</td><td><a href="http://travis-ci.org/s2js/rest" target="_blank"><img src="https://secure.travis-ci.org/s2js/rest.png?branch=master" /></a></tr>
12 <tr><td>Development</td><td><a href="http://travis-ci.org/s2js/rest" target="_blank"><img src="https://secure.travis-ci.org/s2js/rest.png?branch=dev" /></a></tr>
13</table>
14
15
16Getting Started
17---------------
18
19Rest can be installed via [npm](https://npmjs.org/), [Bower](http://twitter.github.com/bower/), or from source.
20
21To install without source:
22
23 $ npm install rest
24
25or
26
27 $ bower install rest
28
29From source:
30
31 $ npm install
32
33Rest.js is designed to run in a browser environment, utilizing [AMD modules](https://github.com/amdjs/amdjs-api/wiki/AMD), or within [Node.js](http://nodejs.org/). [curl](https://github.com/cujojs/curl) is highly recommended as an AMD loader, although any loader should work.
34
35An ECMAScript 5 compatible environment is assumed. Older browsers, ::cough:: IE, that do not support ES5 natively can be shimmed. Any shim should work, although we've tested against cujo's [poly](https://github.com/cujojs/poly)
36
37
38Usage
39-----
40
41Using Rest.js is easy. The core clients provide limited functionality around the request and response lifecycle. The input and response objects are normalized to support portability between browser and server environments.
42
43The response from a client is a promise that is resolved when the remote request finishes.
44
45The core client behavior can be augmented with interceptors. An interceptor wraps the client and transforms the request and response. For example: an interceptor may authenticate a request, or reject the promise if an error is encountered. Interceptors may be combined to create a client with the desired behavior. A configured interceptor acts just like a client.
46
47
48### Making a basic request: ###
49
50```javascript
51define(['rest'], function(client) {
52 client({ path: '/' }).then(function(response) {
53 console.log('response: ', response);
54 });
55});
56```
57
58In this example, you can see that the request object is very simple, it just includes the path. All of the attributes of a request are optional.
59
60The response should look familiar as well, it contains all the fields you would expect, including the response headers (many clients ignore the headers).
61
62
63### Working with JSON: ###
64
65If you're paying attention, you may have noticed that the response.entity in the previous example is a String. Often we need to work with more complex data types. For this, Rest supports a rich set of MIME type conversions with the `mime` interceptor. The correct converter will automatically be chosen based on the Content-Type response header. Custom converts can be registered for a MIME type, more on that later...
66
67```javascript
68define(['rest/interceptor/mime'], function(mime) {
69 var client = mime();
70 client({ path: '/data.json' }).then(function(response) {
71 console.log('response: ', response);
72 });
73});
74```
75
76Before an interceptor can be used, it needs to be configured. In this case, we will accept the default configuration, and obtain a client. Now when we see the response, the entity will be a JS object instead of a String.
77
78
79### Composing Interceptors: ###
80
81```javascript
82define(['rest/interceptor/mime', 'rest/interceptor/errorCode'], function(mime, errorCode) {
83 var client = mime();
84 client = errorCode(client, { code: 500 });
85 client({ path: '/data.json' }).then(
86 function(response) {
87 console.log('response: ', response);
88 },
89 function(response) {
90 console.error('response error: ', response);
91 }
92 );
93});
94```
95
96In this example, we take the client create by the `mime` interceptor, and wrap it in the `errorCode` interceptor. The errorCode interceptor can accept a configuration object that indicates what status codes should be considered an error. In this case we override the default value of <=400, to only reject with 500 or greater status code.
97
98Since the errorCode interceptor can reject the response promise, we also add a second handler function to receive the response for requests in error.
99
100Clients can continue to be composed with interceptors as needed. At any point the client as configured can be shared. It is safe to share clients and allow other parts of your application to continue to compose other clients around the shared core. Your client is protected from additional interceptors that other parts of the application may add.
101
102
103### Custom MIME Converters: ###
104
105```javascript
106define(['rest/mime/registry'], function(registry) {
107 registry.register('application/vnd.com.example', {
108 read: function(str) {
109 var obj;
110 // do string to object conversions
111 return obj;
112 },
113 write: function(obj) {
114 var str;
115 // do object to string conversions
116 return str;
117 }
118 });
119});
120```
121
122Registering a custom converter is a simple as calling the register function on the mime registry with the type and converter. A converter has just two methods: `read` and `write`. Read converts a String to a more complex Object. Write converts an Object back into a String to be sent to the server. HTTP is fundamentally a text based protocol after all.
123
124Built in converters are available under `rest/mime/type/{type}`, as an example, JSON support is located at `rest/mime/type/application/json`. You never need to know this as a consumer, but it's a good place to find examples.
125
126
127Reporting Issues
128----------------
129
130Please report issues on [GitHub](https://github.com/s2js/rest/issues). Include a brief description of the error, information about the runtime (including shims) and any error messages.
131
132Feature requests are also welcome.
133
134
135Running the Tests
136-----------------
137
138The test suite can be run in two different modes: in node, or in a browser. We use [npm](https://npmjs.org/) and [Buster.JS](http://busterjs.org/) as the test driver, buster is installed automatically with other dependencies.
139
140Before running the test suite for the first time:
141
142 $ npm install
143
144To run the suite in node:
145
146 $ npm test
147
148To run the suite in a browser:
149
150 $ npm start
151 browse to http://localhost:8282/ in the browser(s) you wish to test. It can take a few seconds to start.
152
153
154Contributors
155------------
156
157- Scott Andrews <andrewss@vmware.com>
158- Jeremy Grelle <jgrelle@vmware.com>
159
160Please see CONTRIBUTING.md for details on how to contribute to this project.
161
162
163Copyright
164---------
165
166Integration is made available under the MIT license. See LICENSE.txt for details.
167
168Copyright (c) 2012-2013 VMware, Inc. All Rights Reserved.
169
170VMware, Inc.
1713401 Hillview Avenue
172Palo Alto, CA 94304
173
174
175Change Log
176----------
177
1780.8.4
179- Bower installable, with dependencies
180- node client's response.raw includes ClientResquest and ClientResponse objects
181- basicAuth interceptor correctly indicates auth method
182
1830.8.3
184- moving from the 'scothis' to the 's2js' organization, no functional changes
185
1860.8.2
187- requests may be canceled
188- timeout incerceptor that cancels the request unless it finishes before the timeout
189- retry interceptor handles error respones by retrying the request after an elapsed period
190- error interceptor handlers may recover from errors, a rejected promise must be returned in order to preserve the error state
191- response objects, with an error property, are used for client errors instead of the thrown value
192- interceptor response handlers recieve the interceptor's client rather then the next client in the chain
193- interceptor request handlers may provide a response
194- convert modules to UMD format; no functional impact
195- replaced rest/util/base64 with an MIT licenced impl; no functional impact
196
1970.8.1
198- fixed bug where http method may be overwritten
199
2000.8.0
201- npm name change 'rest-template' -> 'rest'
202- introduced experimental HATEOAS support
203- introduced 'location' interceptor which follows Location response headers, issuing a GET for the specified URL
204- default method to POST when request contains an entity
205- response handlers now have access to the request client to issue subsequent requests
206- interceptors may specify their default client
207- renamed `rest/interceptor/_base` to `rest/interceptor`
208
2090.7.5
210- Initial release, everything is new