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: add handler builder to support ioc #511

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

Jujulego
Copy link

@Jujulego Jujulego commented Dec 10, 2022

Add a builder parameter on createHandler to allow dependency injection using inversify.

Syntax with inversify:

const container = new Container({
  autoBindInjectable: true
});

// Create service
@injectable()
export class TestService {
  public getTest() {
    return {
      test: 'successful'
    };
  }
}

// Create handler with injection
@injectable()
class TestHandler {
  public constructor(private readonly service: TestService) {}

  @Get()
  public testData() {
    return this.service.getTest();
  }
}

export default createHandler(TestHandler, () => container.get(TestHandler));

@vercel
Copy link

vercel bot commented Dec 10, 2022

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
next-api-decorators ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 22, 2023 0:48am

@xarielah
Copy link

@Jujulego I'm using tsyringe and it is not needed, you just apply the @autoInjection() decorators and it works.

@Jujulego
Copy link
Author

Hello @xarielah,
Ok for tsyringe, this won't be needed, and I could use property injection with inversify too to make it work. The problem here is with async dependencies (which are not handled by tsyringe) by example injecting data loaded from a file on an api. In this case we cannot use property injection or create a no parameter constructor like what @autoInjection() does, since a constructor cannot be async.
This solution allow a full control over the controller creation, allowing injection of async dependencies, and may be other use cases I didn't think about.

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.

None yet

2 participants