本文介绍了带有Knex JS和RDS Postgres的AWS Lambda的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在做一些研究,但找不到关于在Lambda函数中使用Knex JS的好答案:

I have been doing some research and I'm not able to find a good answer about using Knex JS within a Lambda function:

如何将Knex与AWS Lambda一起使用? #1875

无服务器URL缩短器与Apex和AWS Lambda

在AWS Lambda中使用Promise.all()

这就是我的index.js中的内容:

Here is what I have in my index.js:

const knex = require('knex')({
  client: 'pg',
  connection: {...},
});

exports.handler = (event, context, callback) => {
  console.log('event received: ', event);
  console.log('knex connection: ', knex);

  knex('goals')
    .then((goals) => {
      console.log('received goals: ', goals);
      knex.client.destroy();
      return callback(null, goals);
    })
    .catch((err) => {
      console.log('error occurred: ', err);
      knex.client.destroy();
      return callback(err);
    });
};

我能够在本地很好地连接并执行我的代码,但是在将其部署到AWS时遇到了一个有趣的错误-首次调用始终成功,但之后的所有操作都会失败.我认为这与knex客户端被销毁有关,但随后尝试在下一次调用中再次使用.如果我重新上传index.js,它会恢复为一个呼叫工作,然后失败.

I am able to connect and execute my code fine locally, but I'm running into an interesting error when it's deployed to AWS - the first call is always successful, but anything after fails. I think this is related to the knex client being destroyed, but then trying to be used again on the next call. If I re-upload my index.js, it goes back to working for one call, and then failing.

我相信可以使用promise解决此问题,但这是我第一次与Lambda合作,因此我不熟悉它如何在后续调用中管理与RDS的连接.预先感谢您的任何建议!

I believe this can be resolved somehow using promises but this my first time working with Lambda so I'm not familiar with how it's managing the connection to RDS on subsequent calls. Thanks in advance for any suggestions!

推荐答案

对我来说,它在我的本地计算机上有效,但在部署后却无法使用.我有点被误导了.

For me, it worked on my local machine but not after deploying. I was kind of be mislead.

事实证明,RDS入站源未对我的Lambda函数开放.在> AWS Lambda无法连接到解决方案中找到解决方案RDS实例,但是我可以在本地吗?:将RDS入站源更改为0.0.0.0/0还是使用VPC.

It turns out the RDS inbound source is not open to my Lambda function. Found solution at AWS Lambda can't connect to RDS instance, but I can locally?: either changing RDS inbound source to 0.0.0.0/0 or use VPC.

更新RDS入站源后,我可以将Lambda与Knex一起成功使用.

After updating RDS inbound source, I can use Lambda with Knex successfully.

我正在使用的Lambda运行时是Node.js 8.10,带有软件包:

The Lambda runtime I am using is Node.js 8.10 with packages:

knex: 0.17.0
pg: 7.11.0

下面使用async的代码也对我有用

The code below using async also just works for me

const Knex = require('knex');

const pg = Knex({ ... });

module.exports.submitForm = async (event) => {
  const {
    fields,
  } = event['body-json'] || {};

  return pg('surveys')
    .insert(fields)
    .then(() => {
      return {
        status: 200
      };
    })
    .catch(err => {
      return {
        status: 500
      };
    });
};

希望它将对将来可能遇到相同问题的人们有所帮助.

Hopefully it will help people who might meet same issue in future.

这篇关于带有Knex JS和RDS Postgres的AWS Lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 20:22