rest.js
Interact with a Rest-API. Works on client (browser) and server (node.js).
Installation
$ npm install rest-js
Running tests
If not done yet you first need to install the global dependencies:
$ npm install -g jake browserify brfs istanbul
Then to run the tests do:
$ jake test
To run the test with code coverage:
$ istanbul cover jake test
By default Browser-sides tests will run in the chrome browser. You can override the browser(s) to use by providing a "browser" option containing a comma seperated list of browser executables:
$ jake test browser=chrome,firefox
To skip browser testing do:
$ jake test browser=none
Usage
var rest = ; var restApi = ; restApi;
All methods also return a promise.
CRUD methods
restApi; // GET -> /catsrestApi; // alias to .read restApi; // DELETE -> /cats/10restApi; // alias to .remove restApi; // POST -> /catsrestApi; // alias to .create restApi; // PUT -> /cats/10restApi; // alias to .update
You can also send a rest-request with any available HTTP method using
restApi;
Passing data
You can pass a data-Object within the options.
restApi;
Available constructor options
var restApi = ;
Middlewares
Middlewares or filters allow transormation or manipulation of request and response data.
They are simple callback functions that get passed two or more parameters.
The last parameter is always a callback function that needs to be called, once the filter has done it's work. If you pass an error to the callback it will be passed to the error middleware.
- if using two parameters: request, next
- if using three parameters: request, response, next
- if using four parameters: error, request, response, next
Middlewares are executed in the same order they got appended. So if a previously appended middleware executes you get passed the already transformed data in the next middleware.
Example:
restApi;
You can add middlewares using the .use()
method:
restApi; // add a middleware
You can also remove already appended filters:
restApi; // remove a middleware
Rest auto appends the following filters already:
-
Method-Fallback middleware that adds the '_method' URL parameter containing the method to use for the request. This is an approved convention to workaround the missing capabilities of browsers to send others then GET and POST requests.
-
JSON Request-Data middleware that tries to stringify outgoing data to JSON if the request data type is 'json'.
-
JSON Response-Data middleware that tries to parse incoming response data using JSON.stringify() if the expecte response data type is 'json'.
-
Generic Error middleware that creates an error for each response with a status code >= 400. It tries to detect the error message from the response data.
Available request options
You can pass in options for each CRUD method or Rest.request(). These options are as follows:
restApi;