Router

Router

new Router(optsopt)

Source:

Create a new Router.

Parameters:
Name Type Attributes Description
opts Object <optional>

Options for initializing this Router and the internal find-my-way router.

Properties
Name Type Attributes Default Description
host String <optional>

An optional host for this router. Used when generating URLs. Can include variables, though that's slower and not recommended.

name String <optional>

An optional name for this router. Used when resolving a route for URL generation.

prefix String <optional>

An optional prefix to apply to all routes for this Router.

findMyWay Object <optional>

Options to provide to the internal find-my-way router.

paramwareBeforeDataware Boolean <optional>
false

If this is true, middleware registered for specific params will run before data-based middleware.

mountMiddleware Boolean | Router~dataMiddleware <optional>

Middleware to use for Router#mount instead of Mount. If set to false, this will disable the automatic mount data-based middleware. As a result, Router#mount will not function correctly.

handleOptions Boolean | Router~handleOptions <optional>

Whether or not to handle OPTIONS requests. Optionally takes a function to handle OPTIONS.

handle405 Boolean | Router~handleOptions <optional>

Whether or not to generate 405 responses when there are no matching methods for a route. Optionally takes a function to handle 405s.

Methods

defaultData(key, value) → {Router}

Source:

This allows you to set default data which is used for all routes that do not have existing data set for a specific data-based middleware.

Example
// For an example of how to write a simple cache dataware,
// check out the project README.
router.useData('cache', duration => {
    // duration is the number of seconds
    // <cache logic goes here>
    return cache_middleware;
});

// We default to a 60 second cache.
router.defaultData('cache', 60);

router.get('/', ctx => {
    ctx.body = 'This uses the default cache of 60 seconds: ' + Date.now();
});

router.get('/fast', {cache: 5}, ctx => {
    ctx.body = 'This is only cached for 5 seconds: ' + Date.now();
});
Parameters:
Name Type Description
key String

The data key

value Object

The default value to set. undefined to remove.

Returns:

The Router

Type
Router

METHOD(nameopt, path, optionsopt, …middleware) → {Router}

Source:

Match URL paths to middleware using router.METHOD() where method is an HTTP method, such as GET, POST, or DELETE. The special method router.all() will match all methods.

When a route is matched, the route's options will be available at ctx.state.route.

Route paths are passed directly to an internal find-my-way instance and should be written using that syntax. This syntax, for the most part, mirrors that used by path-to-regexp.

If supplied, hosts are parsed with path-to-regexp. Hosts without variables are checked with simple string comparison while hosts with variables are matched with a regular expression generated by path-to-regexp.

Any variables within the host will be stored in ctx.host_params and ctx.request.host_params.

Example
router
    .get('/', (ctx, next) => {
        ctx.body = "Hello, World!"
    })
    .post('user', '/user/:userID', (ctx, next) => {
        // ...
    })
    .del('/topic/:topicID/message/:messageID', {some_data: false}, (ctx, next) => {
        // ...
    })
Parameters:
Name Type Attributes Description
name String <optional>

A name for this route. Equivilent to setting a name key in options.

path String | Array.<String>

A path or multiple paths that these middleware functions will match.

options Object <optional>

Optional data to associate with the route, including a name and data for data-based middleware.

Properties
Name Type Attributes Description
host String <optional>

Optional host for this specific route. Different methods on the same route must use the same host.

middleware function <repeatable>

Middleware functions to handle this route.

Returns:

The router

Type
Router

middleware() → {function}

Source:

Get a middleware method for adding a Router to Koa.

Example
const router = Router();
app.use(router.middleware())
Returns:

Koa Middleware

Type
function

mount(path, optionsopt, …middleware) → {Router}

Source:

Mount the given middleware at a specific path. This will register the middleware for all HTTP methods on the given route, and strip the path from ctx.path temporarilly when calling the middleware.

Internally, this acts by setting the option {mount: '*'} on the generated route while also ensuring the path ends with /*. This method will not function correctly if the built-in mount middleware is disabled.

Parameters:
Name Type Attributes Description
path String | Array.<String>

The path to mount the middleware at.

options Object <optional>

An optional set of options for the middleware.

middleware function <repeatable>

The middleware function(s) to use

Returns:

The Router

Type
Router

nest(pathopt, router) → {Router}

Source:

Nest another Router as a child of this router, inheriting all of its routes, middleware, etc.

Example
const users = Router({prefix: '/user'});

users.get('/:userID', ctx => {
    // ...
});

router.nest(users);
Parameters:
Name Type Attributes Description
path String | Array.<String> <optional>

The path to nest the router at.

router Router

The router instance to be nested.

Returns:

The Router

Type
Router

param(param, …middleware)

Source:

Use middleware for a named route parameter. This is useful for automatically loading data or performing validation for commonly used route parameters.

Example
router.param('userID', async (userID, ctx, next) => {
    ctx.user = await Users.query().where('id', userID);
    return next();
});

router.get('/user/:userID', ctx => {
    // ... do something with ctx.user
});
Parameters:
Name Type Attributes Description
param String

The name of the parameter to handle.

middleware function <repeatable>

The middleware to apply to that parameter.

register(methods, path, options, …middleware) → {Router}

Source:

Register a new route and update the router's internal state.

Example
router.register('get', '/', null, ctx => {
    ctx.body = "Hello, World!"
})
Parameters:
Name Type Attributes Description
methods String | Array.<String>

The HTTP methods that these middleware functions can handle.

path String | Array.<String>

A path or multiple paths that these middleware functions will match.

options Object | null

Optional data to associate with the route, including a name and data for data-based middleware.

Properties
Name Type Attributes Description
host String <optional>

Optional host for this specific route. Different methods on the same route must use the same host.

middleware function <repeatable>

Middleware functions to handle this route.

Returns:

The Router

Type
Router

setDataExclusive(key, exclusiveopt) → {Router}

Source:

This method allows you to mark a specific key for data-based middleware as exclusive. This will prevent a parent's data-based middleware from being applied to the routes of a nested Router.

The default mount middleware is set to exclusive to prevent multiple copies of the mount middleware being applied to matching routes.

Parameters:
Name Type Attributes Default Description
key String

The data key

exclusive Boolean <optional>
true

Whether or not data-based middleware for the provided key should be exclusive.

Returns:

The Router

Type
Router

sortData(key, sort_valueopt) → {Router}

Source:

This allows you to override the order in which data-based middleware are applied. You can also provide this value when defining your data-based middleware constructors with Router#useData.

Parameters:
Name Type Attributes Default Description
key String

The data key

sort_value Number <optional>
0

A number to use for this data-based middleware when sorting to determine which to apply first. Lower values execute first.

Returns:

The Router

Type
Router

urlFor(name, paramsopt, optionsopt, source_hostopt, source_protocolopt) → {String}

Source:

Generate a URL for the route with the given name.

Routes will inherit the name of the Router that contains them. As a shortcut for accessing other routes in the same namespace, you can start the name passed to urlFor with a period.

urlFor is assigned to the current Koa context and should be used there to ensure namespaces work correctly.

Once the URL has been built (using path-to-regexp) that generated URL and any left over parameters are merged into options and the structure is passed to url.format()

If the Router or specific route is using a host, and a host hasn't been specified in options, the host will be checked against source_host. If the host does not match, an absolute URL will be generated.

Any host variables for the route must be included in params.

Example
const router = Router(),
      user_router = Router({name: 'user', prefix: '/user'});

user_router.get('me', '/me', ctx => {
    ctx.redirect(ctx.urlFor('.id', ctx.state.current_user.id));
});

user_router.get('id', '/:userID', ctx => {
    // ...
});

router.use(user_router);

router.get('/', ctx => {
    ctx.redirect(ctx.urlFor('user.me'));
});
Parameters:
Name Type Attributes Description
name String

The name of the route

params Object <optional>

Parameters to place in the generated URL. Required if the route takes parameters. Any parameter not consumed in the route will be added as a query parameter.

options Object <optional>

Options to pass to url.format().

Properties
Name Type Attributes Default Description
query Object <optional>

Query parameters for the generated URL.

absolute Object <optional>
false

If set to true, the generated URL will always be absolute.

source_host String <optional>

The host from the request that triggered this method.

source_protocol String <optional>

The protocol from the request that triggered this method.

Returns:

The generated URL.

Type
String

use(pathopt, …middleware) → {Router}

Source:

Use the given middleware. Middleware are run in the order they are defined. This can also be used to nest another Router as a child of this router.

Example
router.use(SomeMiddleware);
router.use('/user', SomeUserMiddleware);
router.use(anotherRouter);
Parameters:
Name Type Attributes Description
path String | Array.<String> <optional>

A path or array of paths to limit the middleware to

middleware function | Router <repeatable>

The middleware function(s) to use

Returns:

The Router

Type
Router

useData(key, sort_valueopt, …constructor) → {Router}

Source:

Use constructed middleware on routes with the provided data key. Constructors registered using this method are executed when pre-calculating a route's middleware chain. The constructors are expected to return a middleware function or array of functions. These functions will be run after general middleware registered via Router#use but before the middleware functions registered for a route.

By setting a sort property on the returned middleware method, it is possible to override the sorting for that specific method.

Example
router.useData('headers', headers => {
    return async (ctx, next) => {
        await next();
        ctx.set(headers);
    }
});

router.useData('validation', -1, options => {
    const postFn = (ctx, next) => {
        // This runs after headers
        await next();
    };

    // Make postFn run later
    postFn.sort = 2;

    return [
        async (ctx, next) => {
            // This runs before headers
            await next();
        },
        postFn
    ];
});

router.get('/', {
    headers: {
        'Access-Control-Allow-Origin': '*'
    },
    validation: true
}, ctx => {
    ctx.body = "Hello, World!";
});
Parameters:
Name Type Attributes Default Description
key String

The data key to match

sort_value Number <optional>
0

A number to use for this data-based middleware when sorting to determine which to apply first. Lower values execute first.

constructor function <repeatable>

The middleware constructor function(s) to use

Returns:

The Router

Type
Router

Type Definitions

dataMiddleware(data, route, _store) → {function|Array.<function()>}

Source:

A factory for Koa middleware, acting off of data attached to a specific route. The returned function or functions may have a sort property for overriding the sorting of that specific middleware instance on that specific route.

Example
router.useData('database', options => {
    const connection = database.getConnection(options);

    return async (ctx, next) => {
        const cursor = connection.getCursor();
        ctx.db = cursor;
        try {
            await next();
        } finally {
            cursor.close();
            ctx.db = null;
        }
    }
});

router.useData('validation', options => {
    const methods = [];

    if ( options.query )
        methods.push((ctx, next) => {
            validateQuery(options.query, ctx.query);
            return next();
        });

    if ( options.result ) {
        const fn = async (ctx, next) => {
            await next();
            validateResult(options.result, ctx);
        };

        fn.sort = 2;
        methods.push(fn);
    }

    return methods;
});
Parameters:
Name Type Description
data *

The data attached to a route that triggered the instantiation of this data-ware middleware.

route String

The applicable route

_store Object

The internal data store for the route.

Returns:

Koa Middleware

Type
function | Array.<function()>

handleOptions(ctx, next, store)

Source:

A Koa middleware function that has an additional parameter containing the internal route data, called when a route is matched but the requested method has no handler.

These functions are used for generating 405 Method Not Allowed responses, as well as responses to OPTIONS requests.

Example
const router = Router({
    handleOptions: (ctx, next, store) => {
        ctx.set('Allow', Object.keys(store).join(', ').toUpperCase());
        ctx.status = 204;
    }
})
Parameters:
Name Type Description
ctx Object

The Koa Context

next function

The next middleware in the stack

store Object

The internal route object, with keys for each handled method