Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(tsyringe): add @hono/tsyringe middleware #785

Merged
merged 1 commit into from
Nov 16, 2024

Conversation

elct9620
Copy link
Contributor

This middleware uses tsyringe to provide dependency injection support for Hono and can construct objects with c.var.resolve(MyService)

Example

@injectable()
class Client {
  private readonly apiKey: string;

  constructor(@inject(Config) config: Config) {
    this.apiKey = config.apiKey
  }

  // ...
}

app.use('*', tsyringe(
  (c, container) => {
      container.register(Config, { useValue: new Config(c.env.API_TOKEN)) }
  }
))

app.get('/foo', async (c) => {
  const apiClient = c.var.resolve(Client)
  const reply = await apiClient.hello()
  return c.text(reply)
})

Copy link

changeset-bot bot commented Oct 20, 2024

🦋 Changeset detected

Latest commit: aced1ba

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@hono/tsyringe Minor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@elct9620 elct9620 force-pushed the feat/tsyringe-middleware branch 2 times, most recently from 518382c to 3721f4f Compare October 24, 2024 16:10
@yusukebe
Copy link
Member

Hi @elct9620

Thank you for the PR.

One thing. It's better not to receive a context in Provider. The following is good:

diff --git a/packages/tsyringe/src/index.ts b/packages/tsyringe/src/index.ts
index d883566..1a0c25e 100644
--- a/packages/tsyringe/src/index.ts
+++ b/packages/tsyringe/src/index.ts
@@ -8,11 +8,11 @@ declare module 'hono' {
   }
 }

-export type Provider = (c: Context, container: DependencyContainer) => void
+export type Provider = (container: DependencyContainer) => void
 export const tsyringe = (...providers: Provider[]): MiddlewareHandler => {
   return createMiddleware(async (c, next) => {
     const childContainer = container.createChildContainer()
-    providers.forEach((provider) => provider(c, childContainer))
+    providers.forEach((provider) => provider(childContainer))
     c.set('resolve', <T>(token: InjectionToken<T>) => childContainer.resolve(token))
     await next()
   })

If you want to access the context, you can use callback pattern:

app.use('/tenant/:name/*', async (c, next) => {
  await tsyringe((container) => {
    const tenantName = c.req.param('name')
    container.register(Config, { useFactory: () => new Config(tenantName) })
  })(c, next)
})

The advantage of this method is it can infer types such as c.req.param, c.env, and c.var correctly:

CleanShot 2024-11-14 at 16 24 25@2x

@elct9620
Copy link
Contributor Author

@yusukebe

Thanks for your feedback. I have updated it.

Copy link
Member

@yusukebe yusukebe left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

@yusukebe
Copy link
Member

@elct9620 Thank you!

Let's go with it. I'll merge this and release it now.

@yusukebe yusukebe merged commit 932d651 into honojs:main Nov 16, 2024
1 check passed
@github-actions github-actions bot mentioned this pull request Nov 16, 2024
@elct9620 elct9620 deleted the feat/tsyringe-middleware branch November 17, 2024 01:36
@elct9620
Copy link
Contributor Author

@yusukebe

I am testing the released package, but the compiled module does not included 🤔

截圖 2024-11-17 晚上10 42 32

@yusukebe
Copy link
Member

@elct9620

Fixed in v1.0.1. Try it!

@elct9620
Copy link
Contributor Author

Work correctly, thanks.

@yarabramasta
Copy link

hey @elct9620 sorry to post comment after this is merged since i can't find the original repo. @elct9620 maybe you wanna check this project https://github.com/risen228/tsyringe-neo since tsyringe is likely no longer maintained microsoft/tsyringe#248 (comment)

@elct9620
Copy link
Contributor Author

@yarabramasta thanks for your information. I will follow the updates to decide whether to switch to tsyringe-neo.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants