honojs-middleware/packages/tsyringe
Yusuke Wada 7a401b0850
chore: use the latest eslint and `@hono/eslint-config` (#904)
* chore: use the latest eslint and `@hono/eslint-config`

* update codes
2024-12-25 18:08:43 +09:00
..
src chore: use the latest eslint and `@hono/eslint-config` (#904) 2024-12-25 18:08:43 +09:00
CHANGELOG.md Version Packages (#835) 2024-11-18 11:14:07 +09:00
README.md feat(tsyringe): add @hono/tsyringe middleware (#785) 2024-11-17 05:36:39 +09:00
package.json Version Packages (#835) 2024-11-18 11:14:07 +09:00
tsconfig.json feat(tsyringe): add @hono/tsyringe middleware (#785) 2024-11-17 05:36:39 +09:00
vitest.config.ts feat(tsyringe): add @hono/tsyringe middleware (#785) 2024-11-17 05:36:39 +09:00

README.md

tsyringe middleware for Hono

The tsyringe middleware provides a way to use dependency injection in Hono.

Usage

import "reflect-metadata" // tsyringe requires reflect-metadata or polyfill
import { container, inject, injectable } from 'tsyringe'
import { tsyringe } from '@hono/tsyringe'
import { Hono } from 'hono'

@injectable()
class Hello {
  constructor(@inject('name') private name: string) {}

  greet() {
    return `Hello, ${this.name}!`
  }
}

const app = new Hono()

app.use('*', tsyringe((container) => {
    container.register('name', { useValue: 'world' })
}))

app.get('/', (c) => {
    const hello = container.resolve(Hello)
    return c.text(hello.greet())
})

export default app

With providers

const app = new Hono()

app.use('/tenant/:name/*', async (c, next) => {
    await tsyringe((container) => {
        // Allowing to inject `c.var` or `c.req.param` in the providers
        const tenantName = c.req.param('name')

        container.register(Config, { useFactory: () => new Config(tenantName) })
    })(c, next)
})

Author

Aotokitsuruya https://github.com/elct9620

License

MIT