概要
AWS SDK for Javascript v3 を使って DynamoDB を使う方法を紹介します。
インストール
npm install @aws-sdk/client-dynamodb
テーブルの作成
const { DynamoDBClient, CreateTableCommand } = require("@aws-sdk/client-dynamodb")
const client = new DynamoDBClient({ region: 'ap-northeast-1' })
const params = {
TableName: 'music',
AttributeDefinitions: [
{ AttributeName: 'Artist', AttributeType: 'S' },
{ AttributeName: 'SongTitle', AttributeType: 'S' }
],
KeySchema: [
{ AttributeName: 'Artist', KeyType: 'HASH' },
{ AttributeName: 'SongTitle', KeyType: 'RANGE' }
],
ProvisionedThroughput: {
ReadCapacityUnits: 5,
WriteCapacityUnits: 5
}
}
const command = new CreateTableCommand(params)
try {
await client.send(command)
} catch(err) {
console.log(err)
}
データの書き込み
const { DynamoDBClient, PutItemCommand } = require("@aws-sdk/client-dynamodb")
const client = new DynamoDBClient({ region: 'ap-northeast-1' })
const params = {
TableName: 'music',
Item: {
Artist: { S: 'No One You Know' },
SongTitle: { S: 'Call Me Today' },
AlbumTitle: { S: 'Somewhat Famous' }
}
}
const result = await client.send(new PutItemCommand(params))
データの読み取り
const { DynamoDBClient, GetItemCommand } = require("@aws-sdk/client-dynamodb")
const client = new DynamoDBClient({ region: 'ap-northeast-1' })
const params = {
TableName: 'music',
Key: {
Artist: { S: 'No One You Know' },
SongTitle: { S: 'Call Me Today' }
}
}
const result = await client.send(new GetItemCommand(params))
データの更新
const { DynamoDBClient, UpdateItemCommand } = require("@aws-sdk/client-dynamodb")
const client = new DynamoDBClient({ region: 'ap-northeast-1' })
const params = {
TableName: 'music',
Key: {
Artist: { S: 'Acme Band' },
SongTitle: { S: 'Happy Day' },
},
UpdateExpression: 'SET AlbumTitle = :newVal',
ExpressionAttributeValues: {':newVal': { S: 'Updated Album Title'} }
}
const result = await client.send(new UpdateItemCommand(params))
データの削除
const { DynamoDBClient, DeleteItemCommand } = require("@aws-sdk/client-dynamodb")
const client = new DynamoDBClient({ region: 'ap-northeast-1' })
const params = {
TableName: 'music',
Key: {
Artist: { S: 'No One You Know' },
SongTitle: { S: 'Call Me Today' }
}
}
const result = await client.send(new DeleteItemCommand(params))
テーブルのスキャン
const { DynamoDBClient, ScanCommand } = require("@aws-sdk/client-dynamodb")
const client = new DynamoDBClient({ region: 'ap-northeast-1' })
const params = { TableName: 'music' }
const result = await client.send(new ScanCommand(params))
ローカルのDynamoDBと接続する
あらかじめdocker等でDynamoDBの代わりを用意する
docker run -p 8000:8000 amazon/dynamodb-local -jar DynamoDBLocal.jar -sharedDb
endpoint
として接続先をクライアントのコンストラクタに渡す
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const client = new DynamoDBClient({ endpoint: 'http://localhost:8000' })