LambdaからDynamoDBに接続する。(Node.js)


概要

LambdaにデプロイしたNode.jsからDynamoDBに接続し、データを取得する。
早い話が下記図を実施します。

TBLの準備

下記TBLを用意します。マイグレーション方法はリンクを参考にしてください。

ディレクトリ構成

ディレクトリ構成
~/develop/study/aws/dynamo2 $ tree -I node_modules 
.
├── dynamo.js
├── package.json
├── serverless.yml
└── yarn.lock
dynamo.js
'use strict';
require('dotenv').config()
var AWS = require('aws-sdk');
var documentClient = new AWS.DynamoDB.DocumentClient({
  region: "ap-northeast-1",
  accessKeyId: process.env.ACCESS_KEY,
  secretAccessKey: process.env.SECRET_KEY
});


module.exports.olympic = async (event) => {
  var params = {
    TableName: 'Olympic',
    Key: {
      'Id': 1,
      'Country': '日本'
    }
  };

  var result;
  try {
    result = await documentClient.get(params).promise();
  }
  catch (e) {
    result = e;
  }

 const country = result.Item.Country
 const goldMedal = result.Item.Medal.GoldMedal
 const silverMedal = result.Item.Medal.SilverMedal
 const bronzeMedal = result.Item.Medal.BronzeMedal

 let message = country +'金メダル:' + goldMedal + ' 銀メダル' + silverMedal +' 銅メダル:'+ bronzeMedal

 return {
    statusCode: 200,
    body: JSON.stringify(message),
 };

};
serverless.yml
service: dynamodb2

frameworkVersion: '2'

provider:
  name: aws
  runtime: nodejs12.x
  lambdaHashingVersion: 20201221
  region: ap-northeast-1

plugins:
 - serverless-offline

functions:
  lineWebhook:
    handler: dynamo.olympic
    events:
      - http:
          path: dynamo/webhook
          method: post

ローカル実行

ローカルデプロイ
~/develop/study/aws/dynamo2 $ sls offline start
offline: Starting Offline: dev/ap-northeast-1.
offline: Offline [http for lambda] listening on http://localhost:3002
offline: Function names exposed for local invocation by aws-sdk:
           * lineWebhook: dynamodb2-dev-lineWebhook

   ┌───────────────────────────────────────────────────────────────────────────────┐
   │                                                                               │
   │   POST | http://localhost:3000/dev/dynamo/webhook                             │
   │   POST | http://localhost:3000/2015-03-31/functions/lineWebhook/invocations   │
   │                                                                               │
   └───────────────────────────────────────────────────────────────────────────────┘

offline: [HTTP] server ready: http://localhost:3000 🚀
offline: 
offline: Enter "rp" to replay the last request
実行
~/develop/study/aws/dynamo2 $ curl -XPOST http://localhost:3000/dev/dynamo/webhook
"日本金メダル:17 銀メダル11 銅メダル:11"% 

サーバ実行

サーバデプロイ
~/develop/study/aws/dynamo2 $ serverless deploy
Serverless: Packaging service...
Serverless: Excluding development dependencies...
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading artifacts...
Serverless: Uploading service dynamodb2.zip file to S3 (10.79 MB)...
Serverless: Validating template...
Serverless: Updating Stack...
Serverless: Checking Stack update progress...
..............
Serverless: Stack update finished...
Service Information
service: dynamodb2
stage: dev
region: ap-northeast-1
stack: dynamodb2-dev
resources: 12
api keys:
  None
endpoints:
  POST - https://URL/dev/dynamo/webhook
functions:
  lineWebhook: dynamodb2-dev-lineWebhook
layers:
  None
Serverless: Removing old service artifacts from S3...
Serverless: Deprecation warning: Detected ".env" files. In the next major release variables from ".env" files will be automatically loaded into the serverless build process. Set "useDotenv: true" to adopt that behavior now.
            More Info: https://www.serverless.com/framework/docs/deprecations/#LOAD_VARIABLES_FROM_ENV_FILES