如何将 AWS-SDK DynamoDB 指向本地无服务器 DynamoDB

How to point AWS-SDK DynamoDB to a serverless DynamoDB local

我正在尝试编写一个脚本,该脚本将循环遍历 DynamoDB table 和 运行 批写入命令的项目数组。我的功能很好,但我在使用 DynamoDB 时遇到了问题。如果我可以将我的 AWS.DynamoDB.DocumentClient() 指向我的本地主机 运行ning DynamoDB,那就太好了。有什么建议吗?

也会考虑通过 aws cli 运行 命令的方法,但我不确定该怎么做。我 运行宁 Node.js 所以这可能吗?

这是我的代码:

var AWS = require('aws-sdk');
AWS.config.update({ region: 'eu-central-1' });
var DynamoDB = new AWS.DynamoDB.DocumentClient()
DynamoDB.endpoint = 'http://localhost:8000';
const allItems = require('./resource.json');
const tableName = 'some-table-name';
console.log({ tableName, allItems });
var batches = [];
var currentBatch = [];
var count = 0;

for (let i = 0; i < allItems.length; i++) {
  //push item to the current batch
  count++;
  currentBatch.push(allItems[i]);
  if (count % 25 === 0) {
    batches.push(currentBatch);
    currentBatch = [];
  }
}
//if there are still items left in the curr batch, add to the collection of batches
if (currentBatch.length > 0 && currentBatch.length !== 25) {
  batches.push(currentBatch);
}

var completedRequests = 0;
var errors = false;
//request handler for DynamoDB
function requestHandler(err, data) {
  console.log('In the request handler...');
  return function (err, data) {
    completedRequests++;
    errors = errors ? true : err;
    //log error
    if (errors) {
      console.error(JSON.stringify(err, null, 2));
      console.error('Request caused a DB error.');
      console.error('ERROR: ' + err);
      console.error(JSON.stringify(err, null, 2));
    } else {
      var res = {
        statusCode: 200,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Methods': 'GET,POST,OPTIONS',
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Credentials': true,
        },
        body: JSON.stringify(data),
        isBase64Encoded: false,
      };
      console.log(`Success: returned ${data}`);
      return res;
    }
    if (completedRequests == batches.length) {
      return errors;
    }
  };
}

//Make request
var params;
for (let j = 0; j < batches.length; j++) {
  //items go in params.RequestedItems.id array
  //format for the items is {PutRequest : {Item: ITEM_OBJECT}}
  params = '{"RequestItems": {"' + tableName + '": []}}';
  params = JSON.parse(params);
  params.RequestItems[tableName] = batches[j];

  console.log('before db.batchWriteItem: ', params);

  //send to db
  DynamoDB.batchWrite(params, requestHandler(params));
}

我想出来了,会把它留在这里给任何可能需要它的人。

var { DynamoDB } = require('aws-sdk');
var db = new DynamoDB.DocumentClient({
  region: 'localhost',
  endpoint: 'http://localhost:8000',
});