Andre Coetzee
Andre Coetzee

Reputation: 1310

Returning an Object from middleware function in Node.JS

I am new to Node.JS coming from a Java Background I am using express to build this Rest API . What I am trying to do is build the concept of a manager. I am looking for a elegant way of returning a user object in the following:

users route: user.js

router.get('/find/:email', function(req, res, next){
  userWare.findUserByEmail(req, res, next)
});

middleware/manager: usermiddleware.js

module.exports = {
    findUserByEmail: function(req, res, next) {
        models.core_user.find({
            where:{
                email: req.params.email
            }
        }).then(function(user){
            res.json(user)
        }, function(err){
            res.status(404).json(err);
        });
    },
}

So In this above function I would like to return the user object to the route instead of the json. so that I can create the json from the object in the route. The whole point of this manager class will be to fectch and return objects.

Upvotes: 1

Views: 4615

Answers (1)

crackmigg
crackmigg

Reputation: 5901

What you need to do is call the callback function with the data you need or return the promise.

Callback

user.js

router.get('/find/:email', function (req, res, next) {
    userWare.findUserByEmail(req.params.email, function (err, data) {
        // error as first parameter or null if no error occurred
        if (err) {
            return res.status(404).json(err);
        }
        res.json(user);
    });
});

usermiddleware.js

module.exports = {
    findUserByEmail: function (email, next) {
        models.core_user.find({
            where: {
                email: email
            }
        }).then(
            function (user) {
                // async call of callback with user object
                next(null, user);
            }, 
            function (err) {
                // async call of callback with error
                next(err);
            }
        );
    }
};

Promise

You could also just return the promise returned by your model, then it would look like this:

user.js

router.get('/find/:email', function (req, res, next) {
    userWare.findUserByEmail(req.params.email).then(
        function (user) {
            res.json(user);
        }, 
        function (err) {
            res.status(404).json(err)
        }
    );
});

usermiddleware.js

module.exports = {
    findUserByEmail: function (email) {
        // return the promise to the caller
        return models.core_user.find({
            where: {
                email: email
            }
        });
    }
};

Upvotes: 3

Related Questions