node.jskoa2

Convert raw http response to Koa compatible object?


I have a basic HTTP server created with the Node's http module:

var http = require('http');

http.createServer(function (request, response) {
  response.end();
}).listen(8080);

I'm getting the request and response objects from this raw http server, but I need to use them with some pre-existing Koa middlewares, so I'm looking for something to make Koa read them and return me a context object I can use.

What I use right now is:

const contextCompat = context => ({
 cookies: { get: key => getCookies(context.request)[key] },
  request: context.request,
  state: {},
  throw: (status, message) => {
    throw new Error(status, message);
  },
});

But I would like, instead, to use the built-in Koa logic to wrap my raw context.

Does Koa expose something I can use?


Solution

  • I found out a solution, which makes use of a private API (so it may break).

    const app = new Koa();
    
    // pass the http request and response objects here
    const koaContext = app.createContext(request, response);