fastify-decorators
fastify-decorators copied to clipboard
Undefined when extending from abstract class
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.
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));
});
}
Fix released in v4.0.0-next.3