结合两个lambda函数

时间:2017-08-31 20:44:00

标签: node.js amazon-dynamodb aws-lambda aws-api-gateway

我正在编写一个连接API网关和DynamoDB的代码。它们如下所示。

放数据

var body = JSON.parse(event.body);
    console.log(body.phone)
    var table = "userAddresses";
    var params = {
        TableName: table,
        Item: {
            "phone": body.phone,
            "apartmentNumber": body.apartmentNumber,
            "buildingNumber": body.buildingNumber,
            "state": body.state,
            "zip": body.zip
        }
    }

    docClient.put(params, function (err, data) {
        if (err) {
            console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
        } else {
            console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
            var res = {
                "statusCode": 200,
                "headers": {},
                "body": JSON.stringify(data)
            };
            context.succeed(res);
        }
    });

获取数据

var body = JSON.parse(event.body);
    console.log(body.phone)
    var table = "userAddresses";
    var params = {
        TableName: table,
        Item: {
            "phone": body.phone
        }
    }
    docClient.get(params, function (err, data) {
        if (err) {
            console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
        } else {
            console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
            var res = {
                "statusCode": 200,
                "headers": {},
                "body": JSON.stringify(data)
            };
            context.succeed(res);
        }
    });

在我的API网关中,我创建了资源和方法,并将它们指向相应的函数,但现在我正在考虑使用function putData()function getData()这两种方法创建一个常见的lambda函数并将它们指向适当的方法,而不是指向不同的Lambda函数。我尝试通过关注https://kennbrodhagen.net/2015/12/02/how-to-access-http-headers-using-aws-api-gateway-and-lambda/获取HTTP method,然后写为if(method==="GET"){...} else {...},但遗憾的是,我无法获取方法名称。

请帮我说明如何做到这一点。

由于

2 个答案:

答案 0 :(得分:1)

您必须在API网关中添加一个映射,该映射将传递请求方法值。这可以在每个端点的映射中进行硬编码。

添加它的确切方法取决于当前映射的结构。

本指南应该是一个有用的起点:http://docs.aws.amazon.com/apigateway/latest/developerguide/getting-started-mappings.html

答案 1 :(得分:1)

无需创建自定义映射模板。在"集成请求"对于您的资源,请务必检查"使用Lambda代理集成"复选框。

让我们说你的lambda函数如下:

// NodeJS lambda function

exports.handler = function(event, context, callback) {
  // ...your application code...
};

使用"使用Lambda Proxy集成"启用后,event参数将在您的函数执行时包含http请求详细信息。然后,您将可以访问event.httpMethodhttp://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-set-up-simple-proxy.html#api-gateway-simple-proxy-for-lambda-input-format

// Sample `event` for GET request

{
  "path": "/test/hello",
  "headers": {
      "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
      "Accept-Encoding": "gzip, deflate, lzma, sdch, br",
      "Accept-Language": "en-US,en;q=0.8",
      "X-Forwarded-For": "192.168.100.1, 192.168.1.1",
      "X-Forwarded-Port": "443",
      "X-Forwarded-Proto": "https"
  },
  "pathParameters": {"proxy": "hello"},
  "requestContext": {
      "accountId": "123456789012",
      "resourceId": "us4z18",
      "stage": "test",
      "requestId": "41b45ea3-70b5-11e6-b7bd-69b5aaebc7d9",
      "identity": {
          "accountId": "",
          "sourceIp": "192.168.100.1",
          "userArn": "",
          "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36 OPR/39.0.2256.48",
          "user": ""
      },
      "resourcePath": "/{proxy+}",
      "httpMethod": "GET",
      "apiId": "wt6mne2s9k"
  },
  "resource": "/{proxy+}",
  "httpMethod": "GET",
  "queryStringParameters": {"name": "me"},
  "stageVariables": {"stageVarName": "stageVarValue"}
}

注意:使用代理集成时,传递给lambda函数回调的数据必须按特定模式进行格式化,如下所示:

http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-set-up-simple-proxy.html#api-gateway-simple-proxy-for-lambda-output-format

{
    "isBase64Encoded": true|false,
    "statusCode": httpStatusCode,
    "headers": { "headerName": "headerValue", ... },
    "body": "..."
}