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

@defunctzombie/koa-autorouter

v2.0.2

Published

Autorouter creates a koa router from a hierarchy of files and folders. A route is defined by the location and name of a file within a file system tree rather than string names in your application logic.

Downloads

201

Readme

koa-autorouter

Autorouter creates a koa router from a hierarchy of files and folders. A route is defined by the location and name of a file within a file system tree rather than string names in your application logic.

This module helps me organize my code and routes into smaller logic components while redicing boilerplate to create routers manually.

import Router from '@defunctzombie/koa-autorouter';

const app = new Koa();

const router = new Router({
    root: '/path/to/routes/folder',
})
app.use(router.middleware());

Defining Routes

A route is defined by a file under the routes folder. Files should default export a function which will accept a Route instance on which you can attach handlers to specific HTTP verbs.

Below is an example with two routes: An index route and a status-endpoint route. The index route will receive requests for / and the status-endpoint route will receive requests for /status-endpoint.

/
/index.ts
/status-endpoint.ts

Looking at index.ts

import { Route } from '@defunctzombie/autorouter';

export default (route: Route) => {
    route.get(async (req, res) => {
        res.body = 'Hello World!';
    });
}

And status-endpoint.ts

import { Route } from '@defunctzombie/autorouter';

export default (route: Route) => {
     route.get(async (req, res) => {
        res.body = {
            health: 'good',
        }
     });
};

The Route interface supports all HTTP Verbs (get, put, ...). Here we have defined routes which only support GET requests. If we wanted to support other verbs we would need to invoke the appropriate methods on the route instance.

req and res are the Request and Response instances from the koa context. See the koa documentation on appropriate methods and parameters when accessing those objects.

Parameterized Routes

A parameterized route is a route where part of the url can vary and is not known during route setup. An example would be the route /posts/1234. Here 1234 could be the post ID yet we do not know this ID when we setup our routes.

To define a parameterized route, use [parameterName] when naming the file. For our posts example, we would create a route file posts/[postId].ts. The router will understand [postId] indicates a parameterized route and pass requests to our route.

The route setup is defined as:

export default (route: Route<{ postId: string }>) {
    route.get(async (req, res) => {
        // echo the post id
        res.body = {
            postId: req.params.postId,
        }
    });
}

Notice the additional { postId: string} generic argument to our Route type. This indicates the request expects a parameter called postId. The req instance will be extended with the parameter type inforamtion.

GOTCHA: The request parameter generic argument is not type validated against the route filename. You must ensure the parameter name in the file path matches the argument name.

Passthrough Routes

A passthrough route (aka middleware) is defined by invoking the use method on the route instance.

For example - we want to make sure that all routes under /foo contain a specific header. We would create a route file at foo/index.ts under our route root and implement the use method.

import { Route } from '@defunctzombie/autorouter';

export default (route: Route<{ postId: string }>) {
    route.use(async (req, res, next) => {
        if (!req.get('my-header')) {
            res.status = 403;
            return;
        }
        await next();
    });
}

Ignoring Test Files

If you co-locate your tests with your routes, as shown in this repo under the test-routes folder, you will use the ignorePattern Router option.

const router = new Router({
    root: '/path/to/routes/folder',
    ignorePattern: 'test.ts',
})

The ignorePattern option tests file paths against the regex pattern. If the file path matches, the file is ignored by the router.

Requirements

This module is built with typescript and requires nodejs 10.3+ for ES2018 support.

Typescript declaration support is included.

License

BlueOak-1.0.0