Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Class constructor doesnt execute when passing a function of that class to express middleware

I have this file that is called from another express middleware,
it creates a new OrderController instance that has the function createOrder.

import { Router } from "express";
import { OrderController } from "../../controller/orders.controller";
export const orderRouter = Router();

const orderController = new OrderController();
//Create an order
orderRouter.post("/", orderController.createOrder);

The problem is that a new OrderController is initiated meaning that the constructor is executed, but when this.orderModel accessed inside of createOrder() its undefined.

import { OrderModel } from "../database/model/order.model";

export class OrderController {
  orderModel: OrderModel;

  constructor() {
    this.orderModel = new OrderModel();
  }

  async createOrder(req: Request, res: Response, next: NextFunction) {
    const newOrder = ...

    ...

    const order = await this.orderModel.save(newOrder);

    res.json(order);
  }
}

Any ideas?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The constructor is executed, but the way you pass createOrder loses its reference to this.

Use one of the following two lines to fix this:

orderRouter.post("/", orderController.createOrder.bind(orderController));
orderRouter.post("/", (...args) => orderController.createOrder(...args));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading