express-batch
Description
Middleware for Express 4.x that allows for batched API requests.
It's attached as a handler for a particular route.
If you need to perform several different requests to one API simultaneously, you could combine them all together (in one querystring) and send only one request to the handler's route.
The handler parses requests, and then invokes the relevant handler for each request (the standard app router is used), collects all the responses and sends them back as a JSON object with sections for each response.
Currently, only routes for GET locations are supported.
Example
// app initvar express = ;var expressBatch = ;var app = ; // mount batch middelewareapp; // mount ordinary API endpointsapp; app; // start the appapp;
With this example, a request to http://localhost:3000/api/batch?users=/api/users/49&pi=api/constants/pi&nonexistent=/not/existent/route
will return:
users: result: id: "49" name: "Alice" status: 200 pi: result: 3141592653589793 status: 200 nonexistent: result: "Not Found" status: 404
It is also possible to have nested field-value pairs by passing in an options argument with a custom separator property.
// mount batch handler with optional separator for nested field-value pairsvar options = separator: ';';app; // easily handle batched requests with deep field-value pairsapp;
Limitations
- Tested only with Express 4
- Supports only routes for GET requests.
- Handlers which will bу used beyond the middleware, could use only these methods of response:
res.json()
res.jsonp()
res.jsonp()
res.end()
res.status()
res.sendStatus()
res.sendStatus()
res.setHeader()
- assign value to
res.statusCode
Notes
There are similar packages, but which work using real http requests:
Todo
- Returning headers in batch results
- Add documentation about headers passing
- Support of arrays (
batch?users=/api/users/1&users=/api/users/2
should returnusers: [{id:1}, {id:2}]
) - Support of rest of HTTP methods
- Support of rest of
response
methods