-1
다음 예제에서는 나머지 nodejs 구현에 대해 다음 코드를 사용합니다.
app.jsnodejs의 module.exports에 매개 변수를 전달합니다.
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
는 HTTP 동사를 기반으로 검색 할 예정이다 모델 클래스입니다. 예를 들어, person.get
은 다음을 검색하며 현재 다음과 같은 단일 메소드가 있습니다.
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);
위의 코드에서 var peson_model = require('./models/person_model')(connection);
은 작동하지 않습니다.
연결 변수를 전달하고 모듈을 내보내려면 어떻게해야합니까?
거기에 연결할 수있는 모든 수단은 내가 그것을 응용 프로그램을 넓게하고 싶을 때마다 모델을 가로 질러 그것을 공유하지 않고 명시 적으로 의미가 아니라 연결 변수를 전달할 수 있습니다. 한 번 만들어졌습니다. 나는 크게 대답을 환영합니다 – danielad
사용자가 require ('./ lib.js')를 발행 할 때 (연결)을 포함하는 것을 잊어 버린 경우 어떻게 올바른 오류 메시지를 보냅니 까? 나는 "if connection === undefined then throw"를 함수에 넣으려고했는데 위와 같이 던지면 실행되지 않는다. – PeterT