AWSのDynamoDBにCRUD事始
AWSのDynamoDBにCRUD処理を行うために備忘録です。
初心者の方の参考になるかと思います。
今回は、自分のPCからAWSのDynamoDBに対してCRUD処理を行います。
AWS側の処理
CURD処理を行うためにIAMで処理可能な権限を持つユーザーを作成します。
IAMでやること
① IAMに行きユーザーを作成する
② 「アクセスキー・プログラムによるアクセス」をチェックし次へ
③ 作成したユーザーのDynamoDBにFull Accessできるポリシーを割り当てる
⑥ アクセスキーIDとシークレットアクセスキーを忘れずにメモする
DynamoDBで行うこと
② パーテーションキーとソートキーを作成。今回はid(文字列)とpass(数値)に指定
MyPC 側の処理
自分のPCからCRUD処理を行うために、まずは、AWS-sdkをインストールします。
npm i aws-sdk
その上で次の処理をおこなっていきます。
Create
putを使用して、データをDynamoDBに送リます。
const AWS = require ("aws-sdk");
const client = new AWS.DynamoDB.DocumentClient({
region : "自分のリージョンを設定",
credentials : {
secretAccessKey : "自分のシークレットキー",
accessKeyId : "自分のアクセスキー"
}
});
const data1 = {
id : "test",
pass : 1 ,
url : "https://hogehoge"
}
async function create(data){
const result = await client.put({
TableName : "CRUDtest",
Item : data
}).promise();
console.log(result);
}
Promise.resolve()
.then(() => {
return create(data1);
})
.then(() => {
console.log("complete");
})
.catch((e) => {
console.log("Error発生", e);
});
コンソール上で、実行。
node create.js
Read
getで欲しい情報のidとpassを指定して、情報をDynamoDBから取得します。
const AWS = require ("aws-sdk");
const client = new AWS.DynamoDB.DocumentClient({
region : "自分のリージョンを設定",
credentials : {
secretAccessKey : "自分のシークレットキー",
accessKeyId : "自分のアクセスキー"
}
});
async function read(){
const result = await client.get({
TableName : "CRUDtest",
Key : {
id : "test",
pass : 1
}}).promise();
console.log(result.Item.url);
}
Promise.resolve()
.then(() => {
return read();
})
.then(() => {
console.log("complete");
})
.catch((e) => {
console.log("Error発生", e);
});
コンソール上で、実行。
node read.js
Update
今回はsetを使用してデータを更新します。
const AWS = require ("aws-sdk");
const client = new AWS.DynamoDB.DocumentClient({
region : "自分のリージョンを設定",
credentials : {
secretAccessKey : "自分のシークレットキー",
accessKeyId : "自分のアクセスキー"
}
});
async function update(){
const result = await client.update({
TableName : "CRUDtest",
Key : {
id : "test",
pass : 1
},
UpdateExpression: 'set #a = :x',
ExpressionAttributeNames: {'#a' : 'detail'},
ExpressionAttributeValues: {
':x' : "test"
}
}).promise();
console.log(result);
}
Promise.resolve()
.then(() => {
return update();
})
.then(() => {
console.log("complete");
})
.catch((e) => {
console.log("Error発生", e);
});
コンソール上で、実行。
node update.js
結果が取得できます。
今回は、detailという項目が追加され、そこにtestという文字データが追加されました。
delete
const AWS = require ("aws-sdk");
const client = new AWS.DynamoDB.DocumentClient({
region : "自分のリージョンを設定",
credentials : {
secretAccessKey : "自分のシークレットキー",
accessKeyId : "自分のアクセスキー"
}
});
async function del(){
const result = await client.delete({
TableName : "CRUDtest",
Key : {
id : "test",
pass : 1
}
}).promise();
console.log(result);
}
Promise.resolve()
.then(() => {
return del();
})
.then(() => {
console.log("complete");
})
.catch((e) => {
console.log("Error発生", e);
});
コンソール上で、実行。
node delete.js