npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

koa-detour

v2.3.0

Published

Resource-oriented routing for Koa 2+

Downloads

43

Readme

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.