简体   繁体   中英

passing parameters to module.exports in nodejs

I have the following code for implemetation of nodejs a rest api.
app.js

var connection = require('./database_connector');    
connection.initalized();  //guys connection is i want to pass a connection varible to the model
var peson_model = require('./models/person_model')(connection); //this not working
var app = express();
app.use(bodyparser.urlencoded({extended: true}));
app.use(bodyparser.json());
app.get('/persons/', function(req, res) {
    person_model.get(res); // retrive get results
});
// .............express port and listen

person_model.js is a model class that is supposed to retrieve based on the http verb. For example person.get retrieves the following and currently has a single method as follow.

function Person(connection) {
    this.get = function (res) {
        connection.acquire(function(err, con) {
            con.query('select * from person limit 3', function(err, result) {
                con.release();
                console.log("get called");
                res.send(result);
            });
        });
    };
}
// ** I want to pass a connection variable to the model
module.exports = new Person(connection);

In the code above, var peson_model = require('./models/person_model')(connection); is not working.

How do I pass the connection variable and export the module?

If you return a function from your export, you can pass your parameter.

module.exports = function(connection) {
    return new Person(connection);
};

You will need to set this.connection and use that inside your function though.

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