1
votes

I'm looking to add state to serverless-framework node application running locally. I came across the official DynamoDb docker image, i'd like to use serverless framework with this dynamodb instance running on docker exposed at localhost:8000 without using the sls install dynamodb version.

I have tried using it normally with the nodejs aws-sdk with the endpoint and region configured to local. The new user table is lready created and database is accessible via aws-cli --endpoint localhost:8000 but can't access the dynamodb instance through nodejs aws-sdk

// server.js

const AWS = require('aws-sdk');
AWS.config.update({
  region: 'localhost',
  endpoint: "http://127.0.0.1:8000"
});

const ddb = new AWS.DynamoDB.DocumentClient();

const params = {
    "TableName":tableName,
    "IndexName":"email-index",
    "KeyConditions":{
      "email":{
        "ComparisonOperator": "EQ",
        "AttributeValueList": [{"S":email}]
      }
    }
  };

ddb.query(params, (err,data) => {

    console.log('query', data);  // returns query null
}

//handler.js

const server = require('./server');
const http = require('serverless-http');

module.exports.client = http(server);

// serverless.yml

provider:
  name: aws
  runtime: nodejs10.16.0
  region: ca-central-1
  profile: default

iamRoleStatements:
- Effect: Allow
      Action:
        - dynamodb:DescribeTable
        - dynamodb:Query
        - dynamodb:Scan
        - dynamodb:CreateTable
        - dynamodb:ListTables
        - dynamodb:GetItem
        - dynamodb:PutItem
        - dynamodb:UpdateItem
        - dynamodb:DeleteItem
      Resource: "arn:aws:dynamodb:ddblocal:000000000000:table/user"

plugins:
  - serverless-offline

functions:
  client:
    handler: handler.client
    events:
      - http: GET /
      - http: 'GET /{param+}'
      - http:
          path: /signin
          method: post
          cors: true
      - http:
          path: /signup
          method: post
          cors: true

I expected to get a response from the dynamodb in docker local but the aws-sdk cannot connect to it. The above http events go to express.js which works well.

1

1 Answers

0
votes

Try to update if local

let dynamoDb = new AWS.DynamoDB.DocumentClient();
if (process.env.STAGE === 'dev') dynamoDb = new AWS.DynamoDB.DocumentClient({
    region: 'localhost',
    endpoint: 'http://localhost:8000',
    accessKeyId: 'DEFAULT_ACCESS_KEY',
    secretAccessKey: 'DEFAULT_SECRET'
});