Router

Router is used to direct the flow of update. It accepts as arguments a routing function and, optionally, a Map with predefined routes and handlers. Routing function accepts context and return object with route property set to String value. Handler for a specific route is just another middleware.

As Router object is itself a middleware, routers can be nested, e.g., router1.on('yo', router2). Thus, they allow for very deep, well-structured and flexible logic of updates processing. Possible use-cases include multilevel menus, setting different levels of access for bot users and much, much more

const { Router } = require('opengram')

// Can be any function that returns { route: String }
function routeFn(ctx) {
  return { route: ctx.updateType }
}

const router = new Router(routeFn)

// Registering 'callback_query' route
const middlewareCb = function (ctx, next) { ... }
router.on('callback_query', middlewareCb)

// Registering 'message' route
const middlewareMessage = new Composer(...)
router.on('message', middlewareMessage)

// Setting handler for routes that are not registered
const middlewareDefault = someOtherRouter
router.otherwise(middlewareDefault).

Constructor

new Router(routeFn, routeHandlersopt)

Constructs a router with a routing function and optionally some preinstalled middlewares.

Note that you can always install more middlewares on the router by calling Router#on.

Parameters:
NameTypeAttributesDescription
routeFnfunction

A routing function that decides which middleware to run

routeHandlersMap.<Middleware><optional>

Map object with middlewares

Methods

on(route, …fns) → {Router}

Registers new middleware for a given route. The initially supplied routing function may return this route as a string to select the respective middleware for execution for an incoming update.

Parameters:
NameTypeAttributesDescription
routestring

The route for which to register the middleware

fnsMiddleware<repeatable>

Middleware(s) to register

Throws:
TypeError
Returns:
Type: 
Router

otherwise(…fns)

Allows to register middleware that is executed when no route matches, or when the routing function returns undefined. If this method is not called, then the router will simply pass through all requests to the downstream middleware.

Parameters:
NameTypeAttributesDescription
fnsMiddleware<repeatable>

Middleware(s) to run if no route matches

Throws:
TypeError