A
A
Abc Edc2015-04-21 22:20:14
Node.js
Abc Edc, 2015-04-21 22:20:14

How to call child method?

router

var UserController = require('../controllers/user');
var userController = new UserController();
//Вызовы унаследуемых методов
app.get('/users',userController.findAll.bind(userController));
app.get('/users/:id',userController.findById.bind(userController));
//наверняка неправильный вызов методов прототипа
app.post('/login',userController.checkAuth,userController.login);

//Child
var util = require('util');
var User = require('../models/user').User;
ObjectID = require('mongodb').ObjectID;
var MainController = require('./index');
function UserController  () {
    UserController.super_.apply(this,arguments);
    this.model = User;
};
UserController.prototype =  {
    checkAuth : function(req, res, next){
        if (req.session.user) {
            res.json({"login": req.session.user});
        }
        else{
            next();
        }
    },
    login: function(req, res, next){
        var mail = req.body.mail;
        var password  = req.body.password;
        User.autorize(mail,password,function(err, result, user){
                if (result.login == 'yes'){
                    req.session.user = user._id;
                    res.json(result);
                }
                else{
                    res.json({"login":"no"});
                }
            }
        )
    }
};
util.inherits(UserController, MainController);
module.exports =  UserController;

//Main
function MainController(model) {
    this.model = model;
}
MainController.prototype = {
    findAll: function(req, res) {
        this.model.find({}, function (err, results) {
            if (err)  res.json({"findAll":err});
            res.json(results);
        });
    },
    findById : function(req,res) {
        var id = new ObjectID(req.params.id)
        this.model.findById(id, function (err, results) {
            if (err)  res.json({"findById":err});
            res.json(results);
        })
    },
    create: function(req, res){
        var saver = new this.model(req.body);
        saver.save(function(err,results, affected){
            if (err) throw  err;
            res.json({'create':'yes'});
        });
    },
    update: function(req, res){
    }
};

module.exports = MainController;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya Shatokhin, 2015-04-21
@gleber1

What is wrong with such a record?

function UserController  () {
    MainController.apply(this, arguments);
};

Yes, and ".bind" in routers is superfluous, this should already point to an instance of the class.
why are you overwriting class prototype? you need to expand it:
UserController.prototype.checkAuth = function () { /* ваш код */}
MainController.prototype.findAll = function () { /* ваш код */}

etc.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question