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?
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?
Share Improve this question edited Sep 5, 2016 at 13:56 Daniel Wondyifraw asked Sep 5, 2016 at 13:33 Daniel WondyifrawDaniel Wondyifraw 7,7238 gold badges62 silver badges82 bronze badges1 Answer
Reset to default 4If 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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745355848a4624112.html
评论列表(0条)