next-api-decorators icon indicating copy to clipboard operation
next-api-decorators copied to clipboard

feat: add handler builder to support ioc

Open Jujulego opened this issue 2 years ago • 3 comments

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));

Jujulego avatar Dec 10 '22 14:12 Jujulego

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

vercel[bot] avatar Dec 10 '22 14:12 vercel[bot]

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

xarielah avatar Jan 10 '23 12:01 xarielah

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.

Jujulego avatar Jan 14 '23 11:01 Jujulego