AWS SAM本地+ DynamoDB本地

时间:2019-11-13 13:24:19

标签: node.js docker aws-sam amazon-dynamodb-local

我目前正在使用Docker在DynamoDB Local中测试AWS SAM。

这是我遵循的步骤(主要在互联网上找到)

  1. 使用docker network create local-dev创建新的docker网络。
  2. 运行DynamoDB Local docker run -d -v "$PWD":/dynamodb_local_db -p 8000:8000 --network local-dev --name dynamodb amazon/dynamodb-local。到目前为止,我可以使用AWS CLI创建和列出表。
  3. 然后,我继续运行AWS SAM sam local start-api --docker-network local-dev。一切看起来都还好。
  4. 调用了 lambda.js ,但是对于console.log(err)console.log(data)来说似乎没有结果。

我不确定哪里可能出错。请帮我。预先谢谢你!

lambda.js

const services = require('./services.js');
const AWS = require('aws-sdk');

let options = {
    apiVersion: '2012-08-10',
    region: 'ap-southeast-1',
}

if(process.env.AWS_SAM_LOCAL) {
  options.endpoint = new AWS.Endpoint('http://localhost:8000')
}

const dynamoDB = new AWS.DynamoDB(options);

exports.getUser = async (event, context) => {

    let params = {};

    dynamoDB.listTables(params, (err, data) => {
        if(err) console.log(err)
            else console.log(data)
    })

    return true;
}

template.yaml

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Serverless Resources


Parameters:

  FunctionsCodeBucket:
    Type: String
    Description: CodeBucket
  FunctionsCodeKey:
    Type: String
    Description: CodeKey
  FunctionsCodeVersion:
    Type: String
    Description: CodeVersion
  NodeEnv:
    Type: String
    Description: NodeEnv

Globals:
  Api:
    Cors:
      AllowMethods: "'OPTIONS,POST,GET,DELETE,PUT'"
      AllowHeaders: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,Api-Key,api-key'"
      AllowOrigin: "'*'"
  Function:
    Timeout: 300
    Runtime: nodejs10.x
    MemorySize: 128
    CodeUri: ./ 

Resources:
  DevResources:
    Type: AWS::Serverless::Function 
    Properties:                      
      Handler: "index.routes"
      Environment:
        Variables:
          NODE_ENV: !Ref NodeEnv
          # REGION: !Ref "AWS::Region"

      Policies:
      - Version: '2012-10-17'
        Statement:
        - Action:
          - dynamodb:*
          Effect: Allow
          Resource: "*"
      Events:
        GetUser:
          Type: Api 
          Properties:
            Path: /user
            Method: get

1 个答案:

答案 0 :(得分:1)

您的lambda函数不等待dynamoDB.listTables操作。您可以通过使用dynamoDB.listTables的承诺版本来解决此问题,如下所示:

exports.getUser = async (event, context) => {

  let params = {};

  try {
    const resp = await dynamoDB.listTables(params).promise();
    console.log(resp);
  } catch (err) {
    console.log(err)
  }
};

例如,您可能需要做的另一件事是为dynamodb容器分配一个网络别名(您可以使用--network-alias=<container_name>选项进行设置),让我们将别名设置为dynamodb

docker run -d -v "$PWD":/dynamodb_local_db -p 8000:8000 --network local-dev --network-alias=dynamodb --name dynamodb amazon/dynamodb-local

之后,您可以在lambda函数中使用此网络别名:

if(process.env.AWS_SAM_LOCAL) {
  options.endpoint = new AWS.Endpoint('http://dynamodb:8000')
}