M
M
myspace2017-03-08 22:27:21
JavaScript
myspace, 2017-03-08 22:27:21

How correct is the logic of working with the model?

Good evening. Using the example of choosing a phone from the database, how correct is it to do this?
controller

const indexModel = require('../models/indexModel');
class Index {

    constructor(title) {
        this.title = title;
        this.mainPage = this.mainPage.bind(this);
        this.phone = indexModel.getPhone;
    }

     mainPage(req, res, next) {

         let data = {
             title: this.title,
             user: req.session.userId,
             phone: req.phone
         };

         res.render('index', data);
    }

}
module.exports = new Index('Тайтл');

Model, get phone
const connection = require('../connection/mysql');

class indexModel {

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

    getPhone(req, res, next) {

        connection.query('SELECT `phone` from `etc`', function (error, results, fields) {
            if (error) {
                throw error;
            }

            req.phone = results[0].phone;
            next();
        });

    }
}

module.exports = new indexModel();

Actually, I'm worried about the moment where I write the method from the model that the phone selects into the property of the controller class, and then I substitute this property in the router
var express = require('express');
var router = express.Router();
var index = require('../controllers/index');

router.get('/', index.phone, index.mainPage);

module.exports = router;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly, 2017-03-08
@myspace

It seems to me that the use of classes looks like a bicycle, to create a class, in the constructor of which to call a method and export an instance of the class that will execute this method, well, not tin? Why is this veloanism better than a banal function? What is the advantage of using classes here?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question