2016-07-28 8 views
-1

私はリアルタイムのWebページを作成し、データベースとしてpostgreSQLを使用しようとしています。私はnode.jsを使い、バックエンドのものをビルドするように表現します。これはリアルタイムのWebページであり、非常に頻繁に情報を更新する必要があるので、私は次のようになりますpostgreSQLの、との長い接続維持:クライアントが新しいページに行くときにPostgreSQLを切断する

app.get('/:A/:B', function(req,res){ 

    var A = req.params.A; 
    var B = req.params.B; 
    var client = new pg.Client(config[A][B]); 

    client.connect(function(err){ 
    if (err) { 
     console.log("Error occurred when try to connect the database",err); 
    } 
    else { 
     console.log("Connected to the database"); 
    } 
    }); 
    Do some queries with current database connection... 
} 

を、私は、ブラウザでAとBの値を変更する際の問題は、あると新しいデータベースに接続しようとしましたが、古いデータベースと切断していないので、私のページの情報は古いデータベースのままです。私はノードとウェブ開発には新しいです。クライアントが新しいURLに移動しようとすると、古いデータベースとの接続を解除する方法を教えてもらえますか?

答えて

0

リクエストごとに接続を作成するのは良い方法ではないと思います。 A-Bバリアントのサイズが制限されている場合は、開始時に接続プールを作成する方が適切です。

app.get('/:A/:B', function(req, res, next){ // next to forwarding error 
    var A = req.params.A; 
    var B = req.params.B; 
    var client = new pg.Client(config[A][B]); 

     client.connect(function(err){ 
      if (err) 
       return next(err); // go to error-middleware 

      console.log("Connected to the database"); 

      // Do some queries with current database connection... 
      // Keep it mind that they're also asynchronous, so better way is use promises or async (https://github.com/caolan/async) 

      client.end(function (err) { 
       if (err) 
       next(err); 
      }); 
     }); 
} 

// Error middleware 
app.use(function(err, req, res, next) { 
    console.log(req.url, err.message); 
}) 
関連する問題