alina sireneva
dc08d93d2b
Some checks failed
Tests / e2e (push) Blocked by required conditions
Tests / e2e-deno (push) Blocked by required conditions
Tests / test-deno (push) Successful in 1m53s
Tests / test-bun (push) Successful in 2m1s
Tests / test-node (node22) (push) Successful in 2m8s
Tests / test-node (node20) (push) Successful in 2m10s
Tests / test-node (node18) (push) Successful in 2m16s
Tests / test-web (chromium) (push) Successful in 2m18s
Tests / test-web (firefox) (push) Successful in 2m31s
Tests / lint (push) Has been cancelled
Build and deploy typedoc / build (push) Has been cancelled
Co-authored-by: Kamilla 'ova <me@kamillaova.dev> Co-authored-by: Alina Chebakova <chebakov05@gmail.com> Co-authored-by: Kravets <57632712+kravetsone@users.noreply.github.com> Co-authored-by: starkow <hello@starkow.dev> Co-authored-by: sireneva <150665887+sireneva@users.noreply.github.com>
1.1 KiB
1.1 KiB
Dependency Injection
When scaling up your bot to multiple files, you may find it useful to inject dependencies into the children dispatchers instead of having to pass them around manually.
@mtcute/dispatcher
provides a simple service locator that you can use to inject dependencies:
// for typescript, you need to declare the dependencies
declare module '@mtcute/dispatcher' {
interface DispatcherDependencies {
db: Database
}
}
// create a root dispatcher
const dp = Dispatcher.for(tg)
// inject the database
dp.inject('db', new Database())
// or
dp.inject({ db: new Database() })
// and then add a child dispatcher
import { childDispatcher } from './file2'
dp.addChild(childDispatcher)
// file2.ts
const dp = Dispatcher.child()
dp.onNewMessage(async (ctx) => {
// the dependencies are available in dp.deps
const db = dp.deps.db
await db.saveMessage(ctx.message)
})
export const childDispatcher = dp
::: info
You can only inject dependencies into the root dispatcher (the one created with Dispatcher.for
),
and they will be available in all children dispatchers.
:::