From 4419397548615c62e242219eb473014ceac59919 Mon Sep 17 00:00:00 2001 From: Ilya Semenov Date: Mon, 27 Dec 2021 17:10:30 +0700 Subject: [PATCH] feat: inject ctx.scenes with SceneRouter method BREAKING CHANGE: This removes scenes_control_middleware export. --- README.md | 8 ++------ src/index.ts | 1 - src/middleware.ts | 17 ----------------- src/router.ts | 13 ++++++++++++- 4 files changed, 14 insertions(+), 25 deletions(-) delete mode 100644 src/middleware.ts diff --git a/README.md b/README.md index 30668a0..894a2a9 100644 --- a/README.md +++ b/README.md @@ -12,11 +12,7 @@ yarn add grammy-scenes ```ts import { Bot, Context, session, SessionFlavor } from "grammy" -import { - scenes_control_middleware, - SceneSessionFlavor, - ScenesFlavor, -} from "grammy-scenes" +import { SceneSessionFlavor, ScenesFlavor } from "grammy-scenes" import { scenes } from "./scenes" @@ -35,7 +31,7 @@ bot.use( ) // Inject ctx.scenes -bot.use(scenes_control_middleware(scenes)) +bot.use(scenes.manager()) bot.command("start", async (ctx) => { await ctx.reply(`Welcome here`) diff --git a/src/index.ts b/src/index.ts index 8e38f24..5b71809 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,4 @@ export * from "./manager" -export * from "./middleware" export * from "./router" export * from "./scene" export * from "./types" diff --git a/src/middleware.ts b/src/middleware.ts deleted file mode 100644 index 3ae8ab2..0000000 --- a/src/middleware.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { MiddlewareFn } from "grammy" -import { Writable } from "ts-essentials" - -import { ScenesManager } from "./manager" -import { SceneRouter } from "./router" -import { ScenesFlavoredContext } from "./types" - -/** Middleware that injects ctx.scenes */ -export function scenes_control_middleware( - scenes: SceneRouter -): MiddlewareFn { - return (ctx, next) => { - const ctx2 = ctx as Writable - ctx2.scenes = new ScenesManager(ctx, scenes) - return next() - } -} diff --git a/src/router.ts b/src/router.ts index a2d8432..20865a2 100644 --- a/src/router.ts +++ b/src/router.ts @@ -1,7 +1,8 @@ import { Composer, MiddlewareFn } from "grammy" +import { assert, Writable } from "ts-essentials" // Hack to avoid circular import -import { Scene } from "." +import { Scene, ScenesManager } from "." import { ScenesFlavoredContext } from "./types" /** Scene (or subscene) collector that will call scene by its name */ @@ -44,4 +45,14 @@ export class SceneRouter extends Composer { }) return composer.middleware() } + + /** Middleware that injects ctx.scenes */ + manager(): MiddlewareFn { + return (ctx, next) => { + assert(!ctx.scenes, "ctx.scenes has already been installed.") + const ctx2 = ctx as Writable + ctx2.scenes = new ScenesManager(ctx, this) + return next() + } + } }