zion inc zion inc - 1 month ago 12
TypeScript Question

route class not able to access local function #typescript #express

In the code below I get 'undefined' error for 'loglogMePleasePlease' function.

Could someone please help me out with this.


TypeError: Cannot read property 'logMePleasePlease' of undefined


I am at flabbergasted, this kinda error makes me question everything I have coded so far.

import {Router, Request, Response, NextFunction} from 'express';
import * as fs from 'fs';
import { db } from '../db/lowDb'

export class employeeRoute {
router: Router
constructor() {
this.router = Router();
this.init();
}
init() {
this.router.get('/', this.default);
this.logMePleasePlease('SFDSFSDF');/*This call works fine!*/
}
public logMePleasePlease(err){
console.log(err);
}
public default(req: Request, res: Response, next: NextFunction) {
/*****Error when execution gets to follwing line:
TypeError: Cannot read property 'logMePleasePlease' of undefined
******/
this.logMePleasePlease('asdad');
res.send({
status:'ok',
message:'employee api home'
});
}
}
const employee = new employeeRoute();
export default employee.router;

Answer Source

That's probably because your router messes up the context of the function 'default', that's why this equals undefined.

You can try binding the func to the right context in the constructor:

this.default.bind(this)

But this is messy. Are you sure it's a good idea to have a separate router for every route? I would create the one and only router and provide it to every route class in constructor..

I'm using to following pattern in creating routes taken from one of the popular tutorials, which is a bit arguable because of extensive use of static methods, but works nicely for me:

import { NextFunction, Request, Response, Router } from 'express'


export class IndexRoute {


    static CREATE(router: Router) {
        console.log('[IndexRoute::create] Creating route /');

        router.get('/', (req, res, next) => {
            new IndexRoute().index(req, res, next)
        })
    }


    index(req: Request, res: Response, next: NextFunction) {
        console.log('[IndexRoute::index]');
        const data = { status: 'ok' };
        res.status(200).json(data);
    }

}