I am fairly new to backend and Object Oriented Programming in general, especially JavaScript, and was working on something when I came across this error which says
Cannot read properties of undefined (reading 'handleRequest')
I have a ‘base.controller.ts’ file that contains a function called ‘handleRequest’. The idea is to extend my other Controllers with this Base Controller so that I can minimize code duplication.
Here is my ‘base.controller.ts’ file
import { Response, NextFunction } from "express";
// Define a type for service results
interface IServiceResult {
message: string;
code: number;
data?: any;
}
// BaseController class
export default class BaseController {
handleRequest = async (
serviceFunction: (params: any) => Promise<IServiceResult>,
params: any,
response: Response,
next: NextFunction
): Promise<void> => {
try {
const { message, code, data } = await serviceFunction(params);
response.status(code).json({
status: "ok",
message,
data,
});
} catch (error) {
console.error("Unhandled Error:", error); // Debug logging
next(error);
}
};
}
Here’s an example from my ‘auth.controller.ts’ file.
import { NextFunction, Request, Response } from "express";
import BaseController from "./base.controller";
import {
loginService,
registerService,
logoutService,
statusService,
} from "@/services/auth";
class AuthController extends BaseController {
async login(
request: Request,
response: Response,
next: NextFunction
): Promise<void> {
const { email, password } = request.body;
try {
await this.handleRequest(
loginService,
{ email, password },
response,
next
);
} catch (error) {
next(error);
}
}
async register(
request: Request,
response: Response,
next: NextFunction
): Promise<void> {
const { firstName, lastName, email, password } = request.body;
try {
await this.handleRequest(
registerService,
{ firstName, lastName, email, password },
response,
next
);
} catch (error) {
next(error);
}
}
}
export default new AuthController();
I am pretty confident in building stuff out using the "everything in one file" way but I wanna learn how to do things in a neat and maintainable/manageable fashion.
I tried extending my Auth Controller with my Base Controller, expecting it to have access to methods from the parent class, i.e. Base Controller, but for some reason it is not able to do that.
I suspect somethings wrong with how ‘this’ is bind in JavaScript but not sure how to fix this error.
Also, would love to learn if there is a better way to do this.
2
Answers
This is just a wild guess but it looks like how you declared handleRequest in you abstract class will make it not public so not defined in any inheriting class.
So
this
is referring to your extended/child classAuthController
.As you are trying to refer to a method in the parent
BaseController
class, you would actually want to use a call tosuper
.Since you are trying to call a method that doesn’t exist in
this
class, you are getting undefined.i.e.
actually becomes:
Here is a related SO post