0

router.ts

import UserController from './controllers/UserController'
router.get( '/users', UserController.getAll);

Controller.ts

 class Controller {
    
     async _getAll() { 
         return {user: "test"}
     }
    
 }

export default Controller

UserController.ts

import { NextFunction, Request, Response } from "express"
import Controller from "./Controller";


class UserController extends Controller {
  
    async getAll (req: Request, res: Response, next: NextFunction) {
        const response = await this._getAll() 
        return res.status( 200 ).json( response )
    }

}

export default new UserController( );

My main question is i want to use get function other controllers extends from Controller.ts but getting this error:

TypeError: Cannot read properties of undefined (reading '_getAll') at /private/var/www/project/src/controllers/UserController.ts:8:37

mehmetakkus
  • 631
  • 1
  • 8
  • 25
  • 1
    `router.get( '/users', UserController.getAll);` -> `router.get( '/users', (req: Request, res: Response, next: NextFunction) => UserController.getAll(req, res, next));` or `router.get( '/users', UserController.getAll.bind(UserController));` or you can directly bind the method when attaching it to the instance. – VLAZ Sep 16 '22 at 09:39
  • by the way i tried to use auto-bind package but it's occur this error: – mehmetakkus Sep 16 '22 at 09:56
  • /private/var/www/project/node_modules/ts-node/dist/index.js:851 return old(m, filename); Error [ERR_REQUIRE_ESM]: require() of ES Module node_modules/auto-bind/index.js not supported. – mehmetakkus Sep 16 '22 at 09:57

0 Answers0