AWS自習 3日目「Lambdaチュートリアル DynamoDB」

LambdaからDynamoDBにアクセスします。
サンプルのDynamoDBテーブルの作成は下記を参照。
https://note.com/llc_luck/n/n994ce36eaa31

AWS-SDK

APIを使ってDynamoDBにアクセスするには、AWS-SDKをプログラムから利用します。
Node.jsから利用する場合は、下記の「AWS SDK for JavaScript」を利用します。

npm install

DynamoDB用のSDKをインストールします。

$ ls -la
total 24
drwxr-xr-x   6 kazoo  staff   192 Feb 13 14:55 .
drwxr-xr-x  10 kazoo  staff   320 Feb 13 18:46 ..
-rw-r--r--   1 kazoo  staff     8 Feb 13 14:55 .npmignore
-rw-r--r--   1 kazoo  staff  1130 Feb 13 16:47 app.js
-rw-r--r--   1 kazoo  staff   227 Feb 13 16:50 package.json
drwxr-xr-x   3 kazoo  staff    96 Feb 13 14:55 tests
$ npm install @aws-sdk/client-dynamodb
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN sam_sample@1.0.0 No repository field.

+ @aws-sdk/client-dynamodb@3.51.0
added 73 packages from 12 contributors and audited 73 packages in 33.256s

2 packages are looking for funding
  run `npm fund` for details
found 0 vulnerabilities

package.json

  "dependencies": {
    "@aws-sdk/client-dynamodb": "^3.51.0"
  },

template.yaml 編集

`Policies: AmazonDynamoDBFullAccess` 追加。

・・・
Resources:
  SamSampleFunction:
    Type: AWS::Serverless::Function
    Properties:
・・・
      Policies: AmazonDynamoDBFullAccess      
      Environment:
・・・

DynamoDB 書き込み

下記のファイルを作成。

const { DynamoDBClient, BatchWriteItemCommand } = require("@aws-sdk/client-dynamodb");
const REGION = "REGION";
const ddbClient = new DynamoDBClient({ region: REGION });

const params = {
  RequestItems: {
    samSimpleTable: [
      {
        PutRequest: {
          Item: {
            id: { N: "1" },
            status_of_delivery: { S: "一部納品" },
            ordering_quantity: { N: "100" },
            delivery_quantity: { N: "50" },
          },
        },
      },
      {
        PutRequest: {
          Item: {
            id: { N: "2" },
            status_of_delivery: { S: "完納" },
            ordering_quantity: { N: "200" },
            delivery_quantity: { N: "200" },
          },
        },
      },
    ],
  },
};

const batchWrite = async () => {
  try {
    const data = await ddbClient.send(new BatchWriteItemCommand(params));
    console.log("Success, items inserted", data);
    return data;
  } catch (err) {
    console.log("Error", err);
  }
};

module.exports ={batchWrite};

app.js 変更

前段で追加したJSファイルを読み込みます。

・・・
const { Buffer }  = require('buffer');
const { batchWrite } = require('./ddb');
const user = process.env.LOGINUSER;
・・・
return getRecords
  .then(response => {
・・・
    return records;
  })
  .then((response) => {
    console.log(response);
    return batchWrite();
  })
  .catch(error => {
    console.log(error);
  });

sam deploy

ビルドしてデプロイします。

$ sam build
Building codeuri: sam-sample/ runtime: nodejs14.x metadata: {} functions: ['SamSampleFunction']
Running NodejsNpmBuilder:NpmPack
Running NodejsNpmBuilder:CopyNpmrc
Running NodejsNpmBuilder:CopySource
Running NodejsNpmBuilder:NpmInstall
Running NodejsNpmBuilder:CleanUpNpmrc

Build Succeeded

Built Artifacts  : .aws-sam/build
Built Template   : .aws-sam/build/template.yaml

Commands you can use next
=========================
[*] Invoke Function: sam local invoke
[*] Deploy: sam deploy --guided

$ sam deploy --guided

Configuring SAM deploy
======================

	Looking for config file [samconfig.toml] :  Found
	Reading default arguments  :  Success

	Setting default arguments for 'sam deploy'
	=========================================
	Stack Name [sam-app02]:
	AWS Region [ap-northeast-1]:
	#Shows you resources changes to be deployed and require a 'Y' to initiate deploy
	Confirm changes before deploy [y/N]:
	#SAM needs permission to be able to create roles to connect to the resources in your template
	Allow SAM CLI IAM role creation [Y/n]:
	Save arguments to configuration file [Y/n]:
	SAM configuration file [samconfig.toml]:
	SAM configuration environment [default]:

	Looking for resources needed for deployment: Found!
・・・
Successfully created/updated stack - sam-app02

テスト

Lambdaコンソールからテストを実行します。

DynamoDBからレコード追加を確認。

参考:


いいなと思ったら応援しよう!