AWS Lambda函数和Postgres DB

时间:2019-03-31 12:43:35

标签: node.js postgresql amazon-web-services aws-lambda

这一天,我遇到了aws lambda问题。我需要通过将一个用户名传递给lambda来搜索RDS postgres db,但是在每个测试事件中它都会返回:

"{
  "errorMessage": "RequestId: 070f76a4-41c6-40d1-8ef2-0a84d9c04af0 Process exited before completing request"
}"

尤其是堆栈返回:

  

START RequestId:070f76a4-41c6-40d1-8ef2-0a84d9c04af0版本:$ LATEST   2019-03-31T12:32:19.572Z 070f76a4-41c6-40d1-8ef2-0a84d9c04af0 TypeError:   路径必须是字符串。收到未定义       在assertPath(path.js:28:11)       在Object.join(path.js:1236:7)       在Object.module.exports.getFileName(/var/task/node_modules/pgpass/lib/helper.js:61:16)       在module.exports(/var/task/node_modules/pgpass/lib/index.js:10:23)       在连接。 (/var/task/node_modules/pg/lib/client.js:110:9)       在emitOne上(events.js:116:13)       在Connection.emit(events.js:211:7)       在套接字。 (/var/task/node_modules/pg/lib/connection.js:125:12)       在emitOne上(events.js:116:13)       在Socket.emit(events.js:211:7)END RequestId:070f76a4-41c6-40d1-8ef2-0a84d9c04af0 REPORT RequestId:   070f76a4-41c6-40d1-8ef2-0a84d9c04af0时长:583.72 ms已结算   持续时间:600 ms内存大小:128 MB使用的最大内存:35 MB
  RequestId:070f76a4-41c6-40d1-8ef2-0a84d9c04af0进程在退出之前   完成请求

const AWS = require('aws-sdk');

global.fetch = require('node-fetch');

var Pool = require('pg').Pool;

const psql = new Pool ({

host: '',
user: '',
password: '',
database: 'metadata',
port: 5432
})

function searchUser(username){

return new Promise((resolve, reject) => {

    psql.query("SELECT username FROM utilitator where username LIKE '%$1%'", [username], {

        onSucces: function(res){
            resolve(res.rows);
        },
        onFailure: function(err){
            resolve("err");
        },
    });
});
}

exports.handler = async (event, context, callback) => {
//var body = JSON.parse(event.body);

var username = event.username;

var response = {
    "statusCode": 200,
    "isBase64Encoded": false,
    "body": {},
}

try{
    var result = await searchUser(username).then((result) => {
        return result;
    });

    var statusCode = 200;
    var body = result;
    if(result == "err"){
        statusCode = 400;
        body = "user not found";
    }

    response.statusCode = statusCode;
    response.body = body;

    callback(null,response);
}
catch(e){
    callback(e,{
        "isBase64Encoded": false,
        "headers": {},
        "body": "err",
        "statusCode": 501
    });
}
};

我希望Lambda返回db中所有具有与我相似的用户名的用户。

1 个答案:

答案 0 :(得分:0)

我正在浏览node-postgres docs,但没有找到对onSuccessonFailure事件的引用,但在其中仅发现errres对象回调(但我可能忽略了它):

client.query(text, values, (err, res) => {
  if (err) {
    console.log(err.stack)
  } else {
    console.log(res.rows[0])
    // { name: 'brianc', email: 'brian.m.carlson@gmail.com' }
  }
})

但是,它也支持promise版本,这意味着您不必自己对它进行提示:

try {
  const res = await pool.query(text, values)
  console.log(res.rows[0])
  // { name: 'brianc', email: 'brian.m.carlson@gmail.com' }
} catch(err) {
  console.log(err.stack)
}

这意味着您的searchUser函数应如下所示:

const searchUser = username => {
  return await psql.query('SELECT username FROM utilitator where username LIKE $1', [`%${username}%`])
};

最后,在您的处理程序上,由于您已经在使用Node 8,因此不应将promise和callback混在一起。只需以响应对象内部的字符串化JSON形式返回正文即可,如下所示(为简化起见,省略了错误处理):

exports.handler = async (event) => {
  //const body = JSON.parse(event.body);

  const username = event.username;

  const result = await searchUser(username)

  if (result == "err") {
    return {
      "statusCode": 404,
      "isBase64Encoded": false,
      "body": JSON.stringify({message: 'User not found'}),
    }
  }
  return {
    "statusCode": 200,
    "isBase64Encoded": false,
    "body": JSON.stringify(result),
  }

};