fastify-decorators icon indicating copy to clipboard operation
fastify-decorators copied to clipboard

Undefined when extending from abstract class

Open smiziara opened this issue 3 years ago • 1 comments

When you have 2 controllers and both extends from the same abstract class, that uses a request handler decorator, an undefined exception is raised:

TypeError: Cannot read properties of undefined (reading 'bind')
    at fnode_modules/.pnpm/[email protected]_dlrs5f363l6mumdga4t5jlqvt4/lib/decorators/strategies/controller-type.ts:107:93
    at Array.forEach (<anonymous>)
    at registerHandlers (node_modules/.pnpm/[email protected]_dlrs5f363l6mumdga4t5jlqvt4/lib/decorators/strategies/controller-type.ts:95:12)

Sample:

export abstract class BaseController {
  @GET("/ping")
  async ping(_request: FastifyRequest, reply: FastifyReply): Promise<void> {
    reply.code(200).send("PONG!");
  }
}

Now create 2 other controllers with @Controller and @Get/Post and inherit from this BaseController. Bootstrap them:

server.register(bootstrap, {
  directory: import.meta.url,
  controllers: [AController, BController],
});

If we keep just only a single controller, everything works. Multiple controllers extending the same class, seems to be an issue.

smiziara avatar Aug 23 '22 15:08 smiziara

Changing to something like this seems to work, but i have not tested all possible impacts.

function registerHandlers(
  handlers: IHandler[],
  instance: FastifyInstance,
  controllerInstance: Record<string, (request: FastifyRequest, reply: FastifyReply) => void>,
): void {
  handlers.forEach((handler) => {
    if (controllerInstance[handler.handlerMethod as string])
          instance[handler.method](handler.url, handler.options, controllerInstance[handler.handlerMethod as string].bind(controllerInstance));
  });
}

smiziara avatar Aug 23 '22 15:08 smiziara

Hi there,

Just published v3.14.0. Could you check if issue solved for you now?

L2jLiga avatar Oct 04 '22 09:10 L2jLiga

Fix released in v4.0.0-next.3

L2jLiga avatar Oct 07 '22 22:10 L2jLiga

Released v3.14.1 and v4.0.0-next.4 with more fixes for inheritance.

Closing now

L2jLiga avatar Oct 10 '22 15:10 L2jLiga