Как указать AWS -SDK DynamoDB на бессерверный локальный сервер DynamoDB - PullRequest
0 голосов
/ 04 августа 2020

Я пытаюсь написать сценарий, который будет oop проходить через массив элементов для таблицы 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));
}

1 Ответ

0 голосов
/ 04 августа 2020

Я разобрался и оставлю это здесь для всех, кому это может понадобиться.

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