instantcommerce / next-api-decorators

Collection of decorators to create typed Next.js API routes, with easy request validation and transformation.
https://next-api-decorators.vercel.app
MIT License
412 stars 29 forks source link

feat: add handler builder to support ioc #511

Open Jujulego opened 1 year ago

Jujulego commented 1 year ago

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[bot] commented 1 year ago

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 commented 1 year ago

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

Jujulego commented 1 year ago

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.