0

I'm creating some classes in my project made in NODEJS and in this process I made a class that will be responsible for managing standard contents, in this case I called it "Controller", below I'm placing the model.

class Controller{
    constructor(_model){               
        this.MODEL = _model;
    }
    
    async store(req, res) {     
        try {
            const data = await this.MODEL.create(req.body);

            return res.json(data);
        } catch (error) {
            return res.json({
                status: "error",
                message: `${error.message}`,
            });
        } 
    }
    async index(req, res) {
        try {
            const data = await this.MODEL.findAll();    
            return res.json(data);  
        } catch (error) {              
            return res.json({
                status: "error",
                message: `${error.message}`,
            });
        }    
    }
}

module.exports = Controller;

And my main Users class below:

import User from '../models/User';
import Controller from './Controller';

class Users extends Controller {
  constructor(){    
    super(User);    
  }  
}

export default new Users();

My file route:

import { Router } from 'express';
import UserController from '../controllers/Users';

let routerApi = Router();

routerApi.get('/', (req, res) => {
    res.send('/api');
});

routerApi.get("/user", UserController.index);
routerApi.post("/user", UserController.store);

export default routerApi;

But when I call the "Users.index" method I'm getting the following error:

"Cannot read property 'MODEL' of undefined"
Crazy
  • 346
  • 1
  • 4
  • 17
  • How are you calling `index` method? – Yousaf Nov 18 '21 at 17:48
  • @Yousaf added in post my file route.js where I'am call the method .index – Crazy Nov 18 '21 at 18:17
  • what is `UserController`? if it is a alias of `Users`, then `index` isn't static, and what is `User`? – Nur Nov 18 '21 at 18:22
  • 1
    You need to bind the value of `this` to make sure that the value of `this` inside the `index` method is what it should be. `UserController.index` -----> `UserController.index.bind(UserController)` – Yousaf Nov 18 '21 at 18:23
  • @Yousaf, thanks for your answers, it's works.. Is there another "elegant" way to solve this problem without the need to bind the routes? Or is it just that way? – Crazy Nov 18 '21 at 18:33
  • @Crazy Don't use `class`es if you don't want to bind the methods. – Bergi Nov 18 '21 at 22:14
  • Btw, `new Users();` really should be simplified to `new Controller(User)`. No need for a subclass. – Bergi Nov 18 '21 at 22:14

0 Answers0