3

I have NodeJs restful api made by tutorial. And in my endpoint I want to pass export function. For example:

// main.js
REST_ROUTER.prototype.handleRoutes = function(router, connection, md5) {
    router.get("/create", function(req, res) {
        var query = ... 
        connection.query(query,function(err, row) {...}
    });
}

But I want to do it like this:

// main.js
var example = require('./example.js');

REST_ROUTER.prototype.handleRoutes = function(router, connection, md5) {
    router.get("/create", example.create);
}

// example.js
exports.create = function(req, res) {
    var query = ... 
    connection.query(query,function(err, row) {...}
}

However, my connection is not available in example.js. How can I pass it?

3
  • exports.connection.<stuff>...? Commented Feb 23, 2016 at 7:34
  • @Cerbrus can you explain pls? Commented Feb 23, 2016 at 7:39
  • Just a guess. Don't mind me 😉 Commented Feb 23, 2016 at 7:40

2 Answers 2

3

Something like this might help:

// main.js
var example = require('./example.js');

REST_ROUTER.prototype.handleRoutes = function(router, connection, md5) {
    router.get("/create", example.create(connection));
}

// example.js
exports.create = function(connection) {
    return function(req, res) {
       var query = ... 
       connection.query(query,function(err, row) {...}
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Bind example to create example.create.bind(example,connections)

// main.js
var example = require('./example.js');

REST_ROUTER.prototype.handleRoutes = function(router, connection, md5) {
    router.get("/create", example.create.bind(example,connections));
}

// example.js
exports.create = function(connection, req, res) {
    var query = ... 
    connection.query(query,function(err, row) {...}
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.