如何在链接到API网关的AWS Lambda函数中获取阶段的名称

Ben*_*ier 9 amazon-web-services aws-lambda aws-api-gateway

我在AWS Lambda中配置了以下Lambda函数:

var AWS = require('aws-sdk');
var DOC = require('dynamodb-doc');
var dynamo = new DOC.DynamoDB();
exports.handler = function(event, context) {

    var item = { id: 123,
                 foo: "bar"};

    var cb = function(err, data) {
        if(err) {
            console.log(err);
            context.fail('unable to update hit at this time' + err);
        } else {
            console.log(data);
                context.done(null, data);
        }
    };

    // This doesn't work. How do I get current stage ?
    tableName = 'my_dynamo_table_' + stage;

    dynamo.putItem({TableName:tableName, Item:item}, cb);
};
Run Code Online (Sandbox Code Playgroud)

一切都按预期工作(我每次调用时都会在DynamoDB中插入一个项目).

我希望dynamo表名依赖于lambda部署的阶段.

我的桌子是:

  • my_dynamo_table_staging 为舞台 staging
  • my_dynamo_table_prod 为舞台 prod

但是,如何获取lambda中当前阶段的名称?

编辑:我的Lambda由HTTP通过API网关定义的端点调用

JS1*_*111 13

如果您在API网关上的方法集成请求中选中了"Lambda代理集成",则应该stage从API网关以及stageVariable您配置的任何网关接收.

以下是event配置了"Lambda代理集成"的API网关调用的Lambda函数中的对象示例:

{
"resource": "/resourceName",
"path": "/resourceName",
"httpMethod": "POST",
"headers": {
    "header1": "value1",
    "header2": "value2"
},
"queryStringParameters": null,
"pathParameters": null,
"stageVariables": null,
"requestContext": {
    "accountId": "123",
    "resourceId": "abc",
    "stage": "dev",
    "requestId": "456",
    "identity": {
        "cognitoIdentityPoolId": null,
        "accountId": null,
        "cognitoIdentityId": null,
        "caller": null,
        "apiKey": null,
        "sourceIp": "1.1.1.1",
        "accessKey": null,
        "cognitoAuthenticationType": null,
        "cognitoAuthenticationProvider": null,
        "userArn": null,
        "userAgent": "agent",
        "user": null
    },
    "resourcePath": "/resourceName",
    "httpMethod": "POST",
    "apiId": "abc123"
},
"body": "body here",
"isBase64Encoded": false
}
Run Code Online (Sandbox Code Playgroud)

  • 你如何在 Lambda (java) 中访问它 (2认同)

Ben*_*ier 7

经过多次摆弄后我才设法完成了.这是一个演练:

我假设您已配置API网关和Lambda.如果没有,这是一个很好的指南.你需要第一部分和第二部分.您可以通过单击API网关中新引入的"启用CORS"按钮来跳过第2部分的结尾

转到API网关.

点击这里:

在此输入图像描述

点击这里:

在此输入图像描述

然后展开Body Mapping Templates,输入application/json内容类型,单击添加按钮,然后选择映射模板,单击编辑

在此输入图像描述

并将以下内容粘贴到"映射模板"中:

{
  "body" : $input.json('$'),
  "headers": {
    #foreach($param in $input.params().header.keySet())
    "$param": "$util.escapeJavaScript($input.params().header.get($param))" #if($foreach.hasNext),#end

    #end  
  },
  "stage" : "$context.stage"
}
Run Code Online (Sandbox Code Playgroud)

然后单击"部署API"按钮(这对于API网关中的更改生效很重要)

您可以通过将Lambda函数更改为:

var AWS = require('aws-sdk');
var DOC = require('dynamodb-doc');
var dynamo = new DOC.DynamoDB();

exports.handler = function(event, context) {
    var currentStage = event['stage'];

    if (true || !currentStage) { // Used for debugging
        context.fail('Cannot find currentStage.' + ' stage is:'+currentStage);
        return;
    }

// ...
}
Run Code Online (Sandbox Code Playgroud)

然后调用您的端点.您应该有一个HTTP 200响应,具有以下响应正文:

{"errorMessage":"Cannot find currentStage. stage is:development"}
Run Code Online (Sandbox Code Playgroud)

重要说明:
如果你有一个Body Mapping Template太简单的,如下:{"stage" : "$context.stage"},这将覆盖请求中的参数.这就是为什么bodyheaders钥匙存在于Body Mapping Template.如果不是,您的Lambda无法访问它.