Skip to content

Instantly share code, notes, and snippets.

@bttmly
Created November 1, 2016 04:02
Show Gist options
  • Save bttmly/605e9e8e82f4f59826541a3eb5f5aa1b to your computer and use it in GitHub Desktop.
Save bttmly/605e9e8e82f4f59826541a3eb5f5aa1b to your computer and use it in GitHub Desktop.
class ConnectKoa extends Koa {
callback() {
// compose middleware stack
const fn = compose(this.middleware);
// expose a connect-conforming function
return (req, res, next) => {
// create context
const ctx = this.createContext(req, res);
// dispatch context through middleware stack
return fn(ctx).then(() => {
// if part of the middleware stack is going to handle the response,
// it should announce it has done so by setting ctx.respond = false
if (ctx.respond === false) return ctx;
// otherwise, pass control back to the enlcosing app
if (next && res.statusCode == null) return next();
// as a sanity check, ensure none of the middleware set a status code
// but DIDN'T set ctx.respond = false -- they must do both or none!
throw new Error("ctx.respond not set to `false`, but no status code set");
}).catch(err => {
// if next was provided, pass the error back to the enclosing application
if (next) return next(err);
// otherwise, try to surface the error -- if nobody is waiting on this promise
// it the error will be printed by default (process.onUnhandledRejection behavior)
throw err
});
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment