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

##概要
LambdaにデプロイしたNode.jsからDynamoDBに接続し、データを取得する。
早い話が下記図を実施します。
![スクリーンショット 2021-07-30 12.31.25.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/599049/2ccfaa1b-2163-86ba-1131-72b3d480f214.png)

##TBLの準備
下記TBLを用意します。マイグレーション方法は[リンク](https://qiita.com/kouji0705/items/438e808fdb1b872671d8)を参考にしてください。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/599049/de52ecb5-3f2e-93a9-9c69-77aff7f460f8.png)

##ディレクトリ構成
```shell:ディレクトリ構成
~/develop/study/aws/dynamo2 $ tree -I node_modules 
.
├── dynamo.js
├── package.json
├── serverless.yml
└── yarn.lock
```

```javascript: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),
 };

};
```

```yml: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
```

###ローカル実行
```shell:ローカルデプロイ
~/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
```

```shell:実行
~/develop/study/aws/dynamo2 $ curl -XPOST http://localhost:3000/dev/dynamo/webhook
"日本金メダル:17 銀メダル11 銅メダル:11"% 
```

###サーバ実行
```shell:サーバデプロイ
~/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
```

![スクリーンショット 2021-07-30 13.54.14.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/599049/d2b5ffc3-21e2-edf5-da83-13fab366e4a8.png)