Skip to main content
Module

x/grammy_router/mod.ts>Router

Router middleware for grammY
Latest
class Router
implements MiddlewareObj<C>
import { Router } from "https://deno.land/x/grammy_router@v2.0.0/mod.ts";

A router lets you specify a number of middlewares, each of them identified by a string 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.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 => { ... })

Constructors

new
Router(router: (ctx: C) => MaybePromise<string | undefined>, routeHandlers?: Record<string, Middleware<C>> | Map<string, 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

private
otherwiseHandler: Composer<C> | undefined
routeHandlers: Record<string, Middleware<C>>

Methods

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.

route(route: string, ...middleware: Array<Middleware<C>>)

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