2016-09-05 5 views
-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);は機能しません。

接続変数を渡してモジュールをエクスポートするにはどうすればよいですか?

答えて

3

エクスポートから関数を返す場合は、パラメータを渡すことができます。

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

this.connectionを設定し、機能内で使用する必要があります。

+0

私はそれがアプリケーションの幅広さを望むたびにモデル間で共有することはできません。一度作成された。私は大いに感謝して答えを – danielad

+0

require( './ lib.js')を発行するときにユーザーが(接続)を含むことを忘れた場合、どのように正しいエラーメッセージを送信しますか?私は "if connection === undefined then throw"を上記のように関数に入れてみました。スローは実行されません。 – PeterT

関連する問題