implement express controller class with typescript

后端 未结 2 379
無奈伤痛
無奈伤痛 2021-02-06 07:06

I\'m doing an express app with typescript. The router code is:

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

the user class is



        
2条回答
  •  抹茶落季
    2021-02-06 07:48

    You can use export default and instantiate the controller so it can be used without instantiation in whichever file you've imported the controller.

    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 or auth.routes.ts

    import registerCtrl from '../controllers/auth/register.controller.js';
    
    // ... removed for brevity
    
    router.post('/register', registerCtrl.register);
    

提交回复
热议问题