next-api-decorators
next-api-decorators copied to clipboard
feat: add handler builder to support ioc
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));
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 |
@Jujulego I'm using tsyringe and it is not needed, you just apply the @autoInjection() decorators and it works.
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.