Node.jsでDynamoDBへアクセスする

2017-08-29

Node.js から DynamoDB にアクセスしてみる。

以下の記事を読んだ前提で書く。

環境構築

$ mkdir dynamodb-js
$ cd dynamodb-js
$ yarn init
$ yarn add aws-sdk
$ touch .gitignore
$ aws dynamodb create-table \
  --attribute-definitions '[{"AttributeName":"test_hash","AttributeType":"S"},{"AttributeName":"test_range","AttributeType":"S"}]' \
  --table-name 'test_table' \
  --key-schema '[{"AttributeName":"test_hash","KeyType":"HASH"},{"AttributeName":"test_range","KeyType":"RANGE"}]' \
  --provisioned-throughput '{"ReadCapacityUnits":5,"WriteCapacityUnits":5}'

.gitignore を下記のように編集しておく。

node_modules
.DS_Store
./**/.DS_Store

実装

API Documentを参考のこと。
以下を作成する。

  • app/dynamodb.js
  • app/putItem.js
  • app/getItem.js
  • app/deleteItem.js

DynamoDB入門 で作成したテーブルにアクセスする前提。

app/dynamodb.js

const aws = require("aws-sdk");
const dynamodb = new aws.DynamoDB({region: 'ap-northeast-1'});

module.exports = dynamodb;

app/putItem.js

const path = require('path');
const dynamodb = require(path.join(__dirname, 'dynamodb'));

const params = {
  TableName: "test_table",
  Item:{
    "test_hash": {
      S: "xxxxx3"
    },
    "test_range": {
      S: "yyyyy3"
    },
    "test_value": {
      S: "zzzzz3"
    }
  }
};

dynamodb.putItem(params, (err, data) => {
  if (err) {
    console.error("Unable to add item. Error JSON:", JSON.stringify(err, null, 2));
  } else {
    console.log("Added item:", JSON.stringify(data, null, 2));
  }
});

app/getItem.js

const path = require('path');
const dynamodb = require(path.join(__dirname, 'dynamodb'));

const params = {
  TableName: "test_table",
  Key:{
    "test_hash": {
      S: "xxxxx"
    },
    "test_range": {
      S: "yyyyy"
    }
  },
  AttributesToGet: [
    "test_value"
  ]
};

dynamodb.getItem(params, (err, data) => {
  if (err) {
    console.error("Unable to add item. Error JSON:", JSON.stringify(err, null, 2));
  } else {
    console.log("Added item:", JSON.stringify(data, null, 2));
  }
});

app/deleteItem.js

const path = require('path');
const dynamodb = require(path.join(__dirname, 'dynamodb'));

const params = {
  TableName: "test_table",
  Key:{
    "test_hash": {
      S: "xxxxx"
    },
    "test_range": {
      S: "yyyyy"
    }
  }
};

dynamodb.deleteItem(params, (err, data) => {
  if (err) {
    console.error("Unable to add item. Error JSON:", JSON.stringify(err, null, 2));
  } else {
    console.log("Added item:", JSON.stringify(data, null, 2));
  }
});

実行

$ node app/putItem.js
$ node app/getItem.js
$ node app/deleteItem.js

おすすめ書籍

おすすめ記事