I'm using inversify in a hapijs v20 and typescript.
When I try to bind a dependency in a class that will handle requests like this:
import * as Hapi from '@hapi/hapi'
import { injectable, inject } from "inversify";
import { types } from "../types";
@injectable()
export default class SomeController implements SomeInterface {
private dep: any
public constructor(@inject(types.SomeDependecy) dep: SomeDependecy) {
this.dep = dep
}
public validate(request: Hapi.Request, reply: Hapi.ResponseToolkit): Hapi.ResponseObject {
const result = this.dep.validate(request) // The headache line
return reply.response(result)
}
}
and then inject use this class to register a route like this:
public constructor(@inject(types.SomeController) controller: SomeController) {
this.controller = controller
}
public async register(server: Server) {
await server.route([
{
method: 'POST',
path: '/validate',
handler: this.controller.validate
}
])
}
Everything loads up fine, and instances appear to be created. However when I hit the endpoint I get:
TypeError: Cannot read property 'dep' of undefined
Thrown from the line commented in the controller as the headache line :C
Do you guys know what could be causing this?
After some research I found the answer in this question:
Hapi showing undefined variable inside handler
and changed the registration to this:
await server.route([
{
method: 'POST',
path: '/validate',
handler: (request, reply) => {
return this.controller.validate(request, reply)
}
}
])