aws-sdk と @aws-sdk

aws-sdk@aws-sdk について

v2 と v3の違いらしい

新しいものを作るときにはv3@aws-sdkのほうを採用するほうがいいでしょう

stackoverflow.com

コードの差

dynamoDBの例

参考

What's the AWS SDK for JavaScript? - AWS SDK for JavaScript

v2

var AWS = require("aws-sdk");
// Set the Region
AWS.config.update({region: "us-west-2"});
// Create DynamoDB service object
var ddb = new AWS.DynamoDB({apiVersion: "2006-03-01"});

// Call DynamoDB to retrieve the list of tables
ddb.listTables({Limit:10}, function(err, data) {
  if (err) {
    console.log("Error", err.code);
  } else {
    console.log("Tables names are ", data.TableNames);
  }
});

v3

import { DynamoDBClient, 
           ListTablesCommand 
   } from "@aws-sdk/client-dynamodb";
(async function () {
   const dbclient = new DynamoDBClient({ region: 'us-west-2'});
 
  try {
    const results = await dbclient.send(new ListTablesCommand);
    results.Tables.forEach(function (item, index) {
      console.log(item.Name);
    });
  } catch (err) {
    console.error(err)
  }
})();

v3 おまけ (dynamoDBでアトミックカウンタ)

import {
  DynamoDBClient,
  UpdateItemCommand,
  DynamoDBClientConfig,
} from '@aws-sdk/client-dynamodb';

const config: DynamoDBClientConfig = {
  region: 'ap-northeast-1',
};

const dynamo = new DynamoDBClient(config);

(async function () {
  try {
    const output = await dynamo.send(
      new UpdateItemCommand({
        TableName: 'my-table',
        ReturnValues: 'ALL_NEW',
        Key: {
          result: { S: 'one-status' },
        },
        UpdateExpression: 'ADD #count :incr',
        ExpressionAttributeNames: {
          '#count': 'count',
        },
        ExpressionAttributeValues: {
          ':incr': { N: '1' },
        },
      })
    );
  } catch (err) {
    console.error(err);
  }
})();

上記の例は、my-tableresultというKeyがone-statusという値になっているレコードに対し、countというカラムをインクリメントするという例

参考

dynamoDB dev.classmethod.jp maku.blog