@hono/tsyringe
TypeScript icon, indicating that this package has built-in type declarations

1.0.1 • Public • Published

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

Readme

Keywords

none

Package Sidebar

Install

npm i @hono/tsyringe

Weekly Downloads

90

Version

1.0.1

License

MIT

Unpacked Size

5.09 kB

Total Files

6

Last publish

Collaborators

  • yusukebe