简体   繁体   中英

node.js and routing: emit by class

newbie question is following:

I'm having a hard time to get the EventEmitter to work. I already considered the documentation and several best-practive tutorials like this one: https://code.tutsplus.com/tutorials/managing-the-asynchronous-nature-of-nodejs--net-36183

The problem is, that within the user.js (Class) this.emit() hits nothing. userRoutes.js doesn't trigger any user.on(), and I really don't know why..

Any suggestions are appreciated. Hints for better structuring also. My goals are centralized endpoints (well-readable) and reusing the code for every module (like user or products/orders) within different modules, eg calling to update an order out of the user-endpoint.

So, let's assume, you have your node.js-Server with a module configuration, router and several classes, like this:

/server.js

global.__base = __dirname + "/";

var server = require("http").createServer();
var routes = require("./v2");
var initialize = require(global.__base + "config");
var app = initialize.globalModules();

app.use('/api/v2', routes);

app.listen('8090');

/config.js

var db;

module.exports = {
    globalModules: function() {
        // load the global modules
        var app = require("express")();
        var bodyParser = require("body-parser");
        //setUp app
        app.use(bodyParser.json());
        return app;
    },

    db: function() {
        var mysql = require('mysql');
        var db = mysql.createConnection({
                host:       'localhost',
                user:       'root',
                password:   '',
                database:   'node_docx'
            });
        db.connect(function(err) {
            if (err) throw err;
        });
        return db;
    }
};

/v2/index.js (routes)

var userRoutes = require('./userRoutes');
var routes = require('express').Router();


routes.use("/user", userRoutes);
//routes.use("/product", productRoutes);
//routes.use("/order", orderRoutes);
//...


routes.use('*', function(req, res) {
    res.status(404).send({code: 404, message: 'ERR', data: "Unknown target."});
});


module.exports = routes;

/v2/userRoutes.js

var User = require("./routes/user.js");
var user = new User();
var route = require('express').Router();


route.get("/", function(req, res) {
    user.on('error', function(err) {
        res.status(400).send({code: 900, message: 'ERR', data: err});
    });
    user.on('failure', function() {
        res.status(404).send({code: 901, message: 'ERR', data: "User not found!"});
    });
    user.on('success', function(result) {
        res.status(200).send({code: 200, message: 'OK', data: result});
    });
    user.getAll();
});    

module.exports = route;

/v2/routes/user.js

var util = require('util');
var EventEmitter = require('events').EventEmitter;
var initialize = require(global.__base + "/config");
var db = initialize.db();

function User() {
    EventEmitter.call(this); //edit: added, but has not solved the problem
    var self = this; //solved it!

    function _checkForErrors(error, rows, reason) {
        if (error) {
            self.emit('error', error);
            return true;
        }
        if (rows.length < 1) {
            self.emit('failure', reason);
            return true;
        }
        return false;
    }

    function _getData(error, rows) {
        if (_checkForErrors(error, rows)) {
            return false;
        } else {
            self.emit('success', rows);
        }
    }

    function getAll() {
        db.query("SELECT * FROM patient", _getData);
    }

    this.getAll = getAll;

}


util.inherits(User, EventEmitter);

module.exports = User;

It's quite simple, you forgot EventEmiter.call(this) in function User .

function User() {
    EventEmitter.call(this);

    var self = this;

    function _checkForErrors(error, rows, reason) {
        if (error) {
            self.emit('error', error);
            return true;
        }
        if (rows.length < 1) {
            self.emit('failure', reason);
            return true;
        }
        return false;
    }

    function _getData(error, rows) {
        if (_checkForErrors(error, rows)) {
            return false;
        } else {
            self.emit('success', rows);
        }
    }

    function getAll() {
        db.query("SELECT * FROM patient", _getData);
    }

    this.getAll = getAll;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM