The marmelab blog

Introducing koa-multifetch, a Node.js middleware for REST APIs

Published on 4 November 2014 by Thiery

For the past weeks, I’ve been working on a customer project architectured around a REST API. A mobile application, and a web application (powered by ng-admin) consume the resources exposed by this API. The API is RESTful, and therefore exposed resources mostly match the tables of our data model. The problem is that the mobile application needs several calls to the API to display a given page. And since HTTP/2 is not ubiquitous yet, I had to find a way to let the mobile app get all the necessary data for a given page in a single HTTP batch request.

The goal was to post request like the following:

POST /multi HTTP/1.1
Content-Type: application/json
{
    "product": "/products/1",
    "allUsers": "/users"
} 

And get a response aggregating API responses from the two requested routes (/products/1 and /users):

{ 
    "product": {
        "code":"200",
        "headers":[
            { "name": "Content-Type", "value": "text/javascript; charset=UTF-8" }
        ],
        "body": "{ [product1Data] }"
    },
    "allUsers": {
        "code":"200",
        "headers":[
            { "name": "Content-Type", "value": "text/javascript; charset=UTF-8" }
        ],
        "body": "[{ [user1] }, { [user2] }, ...]"
    }
}

It turns out an Express.js middleware already exists for that purpose, it’s called multifetch. Except the project I’m working on doesn’t use Express, it uses Koa, and Express middlewares are not compatible with Koa.

So I rewrote multifetch for Koa. Today, marmelab is releasing this middleware as an open-source project, named koa-multifetch, so anyone can use it.

Usage is very straightforward:

var koaRoute = require('koa-route');
var multifetch = require('koa-multifetch');
app.use(koaRoute.get('/multi', multifetch));

The source is available on Github at marmelab/koa-multifetch. Your feedback is welcome!

comments powered by Disqus