Implement express controller class using typescript

I am making an express application with typescript. Router Code:

let user = new User();
router.get("/", user.test);

custom class

export class User {
   test(req, res, next) {
      // this === undefined
   }
}

the problem is that this object is undefined inside the testing method. Is there a better way to implement express routing?

+4
source share
2 answers

You need to use the binding function to save the scope thiswhen calling the method:

let user = new User();
router.get("/", user.test.bind(user));

Or you can do it in the constructor User:

export class User {
    constructor() {
        this.test = this.test.bind(this);
    }

    test(req, res, next) {
        ...
    }
}

Another option is to use the function:

let user = new User();
router.get("/", (req, res, next) => user.test(req, res, next));
+11
source

export default , , .

register.controller.ts

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

class Register {

    constructor() {    
      this.register = this.register.bind(this);
    }

    register(req: Request, res: Response, next: NextFunction) {
      // ... removed for brevity
    }
}

export default new Register();

server.ts auth.routes.ts

import registerCtrl from '../controllers/auth/register.controller.js';

// ... removed for brevity

router.post('/register', registerCtrl.register);
+1

Source: https://habr.com/ru/post/1657598/


All Articles