簡體   English   中英

如何將 AWS-SDK DynamoDB 指向本地無服務器 DynamoDB

[英]How to point AWS-SDK DynamoDB to a serverless DynamoDB local

我正在嘗試編寫一個腳本,該腳本將循環遍歷 DynamoDB 表的項目數組並運行批量寫入命令。 我的功能很好,但我在使用 DynamoDB 時遇到了問題。 如果我可以將我的 AWS.DynamoDB.DocumentClient() 指向運行 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',
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM