如何使用PG获取Node JS中client.query的值?

时间:2017-06-16 05:51:54

标签: javascript node.js postgresql express pg

我正在使用node.js并与postgresql建立数据库连接。 我的dbConfig.js看起来像: -

var pg = require('pg');
var client  = new pg.Client({
    host:'myhoost',
    port:'5432',
    user:'myuser',
    password:'mypass',
    database:'mydb',
    ssl:true
});
client.connect();
module.exports.myconnection = client;

我的api.js文件如下: -

var dbConnect = require('./dbConfig.js');
var client = dbConnect.myconnection;
var ser = function(value) {
    var query = "SELECT * FROM tbl_api WHERE apikey = '" + value + "'";

    client.query(query, function(err, result) {
        var res = true;
        if (err) {
            var res = false;
        } else {
            if (result.rowCount > 0) {
                res = true;
            } else {
                res = false;
            }
        }
       return res;
    });
};
module.exports.checkAPI = ser;

我的api.js看起来像: -

var express = require('express');
var app = express();
var apiCheck = require('./api.js');


//APIKey Generator check api
app.get('/apicheck/:apikey', function(request, response) {
    var value = request.params.apikey;
    var result = apiCheck.checkAPI(value);
    response.send(result);
});

我希望将client.query中的res转换为结果变量。我在mysqljs issue找到了同样的问题,但我仍然无法解决这个问题。

1 个答案:

答案 0 :(得分:1)

我们需要回调才能返回回复,解决此问题的方法之一是使用promises,如下所示:

var ser = function(value) {
    var query = "SELECT * FROM tbl_api WHERE apikey = '" + value + "'";
    return new Promise(function (resolve, reject) {
       client.query(query, function(err, result) {         
           if (err) {
              return reject(err);
           } else {
              if (result.rowCount > 0) {
                  return resolve(true);
              } 
           }
           return resolve(false);
       });
   });
};
module.exports.checkAPI = ser;

api.js更改为:

var express = require('express');
var app = express();
var apiCheck = require('./api.js');


//APIKey Generator check api
app.get('/apicheck/:apikey', function(request, response) {
    var value = request.params.apikey;
    apiCheck.checkAPI(value)
      .then(function(result) { response.send(result); })
      .catch(function(err) { response.send(err); });
});