如何在处理程序功能之外访问全局范围中的阶段

时间:2019-07-04 16:19:48

标签: amazon-web-services aws-lambda aws-api-gateway

我希望能够访问在全局范围内(即在处理函数之外)调用的API GW阶段的名称。

在我的Lambda中,我想在全局范围内创建数据库连接池,以便它有可能被后续Lambda调用重用(从而潜在地提高了此类后续调用的性能)。连接池显然是由配置驱动的-我将需要能够为每个阶段使用不同的配置值(并且我将根据该阶段名称访问适当的值)。

麻烦的是,直到我进入实际的处理程序调用(在事件对象层次结构中提供)之前,我似乎找不到任何确定阶段名称的方法。

我希望能够做这样的事情:

const stageName = <????how to get this???>;
const config = require(`./${stageName}/config`);
const pool  = mysql.createPool({
    connectionLimit : config.dbconnectionLimit,
    host            : config.dbhost,
    port            : config.dbport,
    user            : config.dbuser,
    password        : config.dbpassword,
});

exports.handler = async (event, context) => {
 let response = {};

 // NOTE: I can easily access the stageName here as event.context.stage
 // as well as any stageVariables under event['stage-variable'].<stageVariableName>
 // However, this is too late to realize the potential performance benefit across
 // subsequent lambda invocations by creating the DB pool in global scope 
 // as opposed to locally within the handler itself

 // ... lambda implementation here (omitted for brevity)  

 return response;
};

0 个答案:

没有答案