Giter VIP home page Giter VIP logo

koa-detour's Introduction

koa-detour

Build Status Coverage Status

KoaDetour is an expressive router for Koa v2 applications. NOTE: this project is NOT versioned according to Koa's versioning scheme. Specifically, all versions are intended only to work with Koa 2.0.0+.

Detour is different from sinatra-style routers (like express's router) because you route urls to objects (that have HTTP methods and resource-level middleware) instead of to HTTP methods directly.

Rationale: If you have multiple http methods implemented for a given url (like a lot of APIs do), this style of routing will be much more natural and will vastly improve your code organization and re-use, and better composition and factoring of middleware. With object routing, it's much simpler to keep the related handlers together, but separated from unrelated handlers (often even in another file/module).

Basic Example

const app = new Koa();
const router = new KoaDetour();
app.use(router.middleware());
router.route("/user", {
  GET (ctx) {
    ctx.body = "GET works!";
  },
  // obviously you'll almost always do something asynchronous in a handler.
  // so, just return a promise here and the router will wait on it
  POST (ctx) {
    return createUser(ctx.req.body)
      .then(user => ctx.body = user);
  },
  // or just use `async` functions!
  async PUT (ctx) {
    const user = await updateUser(ctx.req.body);
    ctx.body = user;
  },
});

Note here that the HTTP handlers (GET and POST) in this example do not receive a next function like normal Koa middleware. This is because there is a distinction between routes and middleware -- routes should be terminal. They handle the request and send a response, or they error, which will be picked up by a downstream error handler. Either way, no other HTTP handler is going to run.

Path parameters

// path parameters (indicated by colons) are available at `ctx.params`
// this is a change from detour, which used `req.pathVars`
router.route("/user/:id", {
  GET (ctx) {
    ctx.body = `GET works: ${ctx.params.id}`
  },
});

Resource-based middleware

The middleware stack for detour runs after the route has been determined, but before any other processing. The entire routed resource object will be available at ctx.resource if you want to do any special handling in your middleware that are related to its contents. Middleware functions can return Promises (or be async, which amounts to the same thing). Interestingly, middleware functions do not receive a next argument to continue processing. Rather, the pattern should be to throw an error (or reject the returned promise) when something goes awry that should cause the main HTTP verb handler to not run.

This makes Detour extremely extensible on a resource-by-resource basis. For example, if you write a resource object like this:

router.route("/user/:id", {
  mustBeAuthenticated: true, // <-- note this property
  GET (ctx) {
    ctx.body = `GET works: ${ctx.params.id}`
  },
});

You might have a middleware like so:

router.use(function (ctx) {
  if (ctx.resource.mustBeAuthenticated && !ctx.user) {
    throw new Error("Not authenticated!");
  }
});

The declarative style of { [middlewareName]: value } has many advantages. However, for more complex cases, you may want to compose functions. Here's one way that might work

const any = fns => async ctx => {
  const results = await Promise.all(fns.map(f => f(ctx)));
  return results.some(Boolean);
}

// message route can be accessed by admins, sender, or recipient
// we implement these predicates elsewhere and share the logic across
// different endpoints, in different configurations, depending on
// the intended access control rules.
router.route("/message/:id", {
  hasAccess: any([
    userIsAdmin,
    userIsSender,
    userIsRecipient,
  ]),
  GET () { /* implementation */ },
})

router.use(async function (ctx) {
  if (ctx.resource.hasAccess) {
    const ok = await ctx.resource.hasAccess(ctx);
    if (!ok) throw new Error("Access not allowed!");
  }
});

All middleware and HTTP handlers are executed in promise chains, so it's safe to throw an error like the one above -- it won't crash the process! However, in this case, Koa will send a 500 response automatically, which is not the correct status code in this situation. Read on...

Handling responses

In Koa's built-in middleware stack, layers are intended to imperatively manipulate the context object. Any values returned from a middleware layer are discarded -- all communication between layers happens through the context object. However, the Detour model of route matching is explicitly terminal. One or zero routes match a request, and if it is one, then that route is responsible for providing the entirey of the HTTP response. This means that the function from router.middleware() actually returns the value the resource provided. This can be used elegantly to unify HTTP response sending:

// this simplified example sends whatever comes out of the route as a 200
const mw = router.middleware();
app.use(async function (ctx, next) {
  try {
    const result = await mw(ctx, next);
    ctx.body = result;
    ctx.status = 200;
  } catch (err) {
    ctx.status = err.status || 500;
    ctx.body = { error: err.message };
  }
});

This approach makes handlers cleaner, as they don't have to imperatively manipulate the context object, and can rather just return a value. response-objects library is built specifically for this purpose.

koa-detour's People

Contributors

bttmly avatar cainus avatar hakubo avatar peterkhayes avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

koa-detour's Issues

issues with `handleSuccess` and `handleError`

  • having handle(event, fn), handleSuccess(ctx, result), and handleError(ctx, err) is confusing!
  • the functionality of handleSuccess and handleError can be implemented without library-level hooks โ€“ users simply do the following
const app = new Koa();
const router = new Detour();
const middleware = router.middleware();
app.use(function (ctx) {
  return middleware(ctx)
    .then(result => successHandler(ctx, result))
    .catch(err => errorHandler(ctx, err));
});

In fact, this is how it's implemented in the library, and avoiding having the library handle it is better for a couple reasons:

  • smaller API surface area
  • more flexible (i.e. complex .then/.catch schemes are possible when not hidden inside library)

There is a downside however โ€“ the most common case for handleSuccess/handleError would probably be for other library code to install those handlers and have the whole thing be mostly transparent to the user. But it can still be something like app.use(responder(router)) but it's a little wonky because we're using app.use rather than router.use

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.