Router
A router lets you specify a number of middlewares, each of them identified by a key. You can then pass a routing function that decides based on the context which middleware to choose by returning one of the keys.
const router = new Router(ctx => {
// determine route to pick here
return 'key'
})
router.route('key', ctx => { ... })
router.route('other-key', ctx => { ... })
router.route(42, ctx => { ... }) // numbers and symbols work
router.otherwise(ctx => { ... }) // called if no route matches
bot.use(router)If you use a custom context type for your bot, you need to pass it when constructing the Router instance, too.
const router = new Router<MyContext>(ctx => { ... })Implements
MiddlewareObj<C>Type Parameters
C
C extends ContextConstructors
Router(router: (ctx: C) => MaybePromise<PropertyKey | undefined>, routeHandlers: Record<PropertyKey, Middleware<C>> | Map<PropertyKey, Middleware<C>>);Constructs a router with a routing function and optionally some preinstalled middlewares. Note that you can always install more middleware on the router by calling route.
Properties
routeHandlers
routeHandlers: Record<PropertyKey, Middleware<C>>;Methods
route
route(route: PropertyKey, ...middleware: Array<Middleware<C>>);
Registers new middleware for a given route. The intially supplied routing function may return this route to select the respective middleware for execution for an incoming update.
otherwise
otherwise(...middleware: Array<Middleware<C>>);
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.
middleware
middleware(): MiddlewareFn<C>;