0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Node]AWS LambdaからDynamoDBを操作する

Last updated at Posted at 2021-05-19

こんにちは takeです。

今回はnodeでAWS Lambda関数を作成しました。(DymanoDBも触りました)

今後開発する際のテンプレートとして残しておきたいと思います。

(今回はDynamoDBのデータを取得しています)

index.js
const AWS = require("aws-sdk");
// DBと接続 (regionを指定するとaws accountに紐づくDynamoDBに接続されます。)
const dynamoDB = new AWS.DynamoDB.DocumentClient({
    // region は人によって変わります。日本だとap-northeast-1かな?
    region: "ap-northeast-1"
});
exports.handler = async (event) => {
    //DynamoDB のクエリを記載する
    let getDatas = async (argument) => {
        const params = {
            // 操作するテーブルの名前を指定
            TableName: "Table Name",
            // 条件式を記載 #key = :key
            KeyConditionExpression: "#key = :key",
            // 条件式に出てきた変数と実際のDBのテーブルの要素を結合 #keyはDBのId
            ExpressionAttributeNames: { '#key':'Id'},
            // 条件式に出てきた変数と関数内の変数を結合 :keyはargument
            ExpressionAttributeValues: {':key':argument},
            // 検索する際のsort
            ScanIndexForward: true,
        };
        return await dynamoDB.query(params).promise();
    };

    //クエリを実行
    let key = "sample"
    let data = await getDatas(key);
    // 取得結果をパース
    data = data.Items;

    // ここで取得したデータをコネコネ

    //レスポンスを作成
    const response = {
        statusCode: 200,
        headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
        },
        body:data,
    };
    return response;
};
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?