Instructions for removing all entries from a DynamoDB table

I am facing a challenge with deleting multiple items from a DynamoDB table. While the documentation suggests dropping and recreating the whole table, I want to avoid this approach as my table was created using AWS Amplify and I don't want to risk disrupting other components in my stack.

After exploring the DynamoDB API and utilizing the aws-sdk in JavaScript, I have successfully managed to delete single items from the database. However, I am struggling to extend this functionality to delete multiple items at once.

// Delete single item:
import { DeleteItemCommand } from "@aws-sdk/client-dynamodb";
import { ddbClient } from "./dynamoDbClient";

const tableName = "myTableName";
const itemId = "12f10644-546c-45f4-8309-c208061e9737";

export async function deleteItemDynamoDb() {
  const command = new DeleteItemCommand({
    TableName: tableName,
    Key: {
      id: {
        S: "12f10644-546c-45f4-8309-c208061e9737",
      },
    },
  });
  const response = await ddbClient.send(command);
}

Answer №1

Struggling with implementing the BatchGetItemCommand for retrieving multiple records from a table, I've devised a workaround by merging AppSync and DynamoDB:

export async function listCardsIncDeleted(): Promise<Card[]> {
  const getCardQueryString = `query listCards {
  listCards(limit:500) {
    items {
      id
      name
      _deleted
      _version
      status
    }
  }
}`;
  try {
    const response = (await appSyncClient.query({
      query: gql(getCardQueryString),
      fetchPolicy: "network-only",
    })) as {
      data: { listCards: { items: Card[]; __typename: "ModelCardConnection" } };
    };
    const { items } = response.data.listCards;
    console.log({ items });

    return items;
  } catch (error) {
    console.log(error);
    throw new Error("ERROR");
  }
}

async function deleteAllTimes(arrayOfCardObjects: { id: string }[]) {
  let count = 0;
  for await (const curCard of arrayOfCardObjects) {
    await new Promise((resolve) => setTimeout(resolve, 50));
    const deleteResponse = await deleteById(curCard.id);
    count++;
    console.log({ deleteResponse, curCardId: curCard.id, count });
  }
  return count;
}
async function listAppSyncThenDelete() {
  const listOfCards = await listCardsIncDeleted();
  const deletedAll = deleteAllTimes(listOfCards);
  return deletedAll;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Add a text to the values in a column of a table when the IDs are the same

I am working on a project that involves updating a table based on a data change. The table has a column for ID and when the ID matches a specific variable, I need to append the word 'Updated!' next to it in the table cell. However, the code I hav ...

Discover the magic of Bootstrap 3.0 Popovers and Tooltips

I'm struggling with implementing the popover and tooltip features in Bootstrap. While I have successfully implemented drop downs and modals, the tooltips are not styled or positioned correctly as shown in the Bootstrap examples, and the popover featur ...

Using jQuery AJAX to Redirect to a 404 Page in Case the Load Method Encounters Failure

My website utilizes AJAX to load all pages using the jQuery load method. I modified this tutorial to work with Wordpress. The issue I am facing now is that when the load method encounters an error (such as a 404 due to a broken link), the AJAX transition ...

What is the best way to pass a variable between different routing functions?

I am currently developing a server-side parser for an API. Each GET request made to my website must first initiate a request to the API, and since this request is always the same, I would like to encapsulate it within its own function. What is the best wa ...

A distinctive noise is heard when hovering over multiple instances of a div

I'm trying to implement a feature where a unique sound plays when hovering over a specific div element with a particular class (.trigger). However, I am encountering an issue where multiple instances of this div class result in the same sound being pl ...

Error-free ngClick doesn't trigger AngularJS controller method

I am struggling to trigger the removePlayer(playerId) method upon clicking a button. However, it seems that the method is not being called, as I have placed a console.log() statement at the top and the console remains empty. This situation has left me puz ...

Having trouble with a basic select tag and options not functioning properly in Chrome browser

I encountered an issue where I am unable to expand a simple select tag in Chrome. <select id="filterCategory" class=""> <option>1</option> <option>2</option> <option>3</option> <option>4</option ...

Why does my computed property become undefined during unit testing of a head() method in Vue.js with Nuxt.js?

In my Vue.js + Nuxt.js component, I have implemented a head() method: <script> export default { name: 'my-page', head() { return { title: `${this.currentPage}` }; }, ... } </script> ...

Develop a descriptive box for a radio button form using jQuery

I am working on creating a form with simple yes/no questions. If the answer is no, no explanation is needed. However, if the answer is yes, I want to insert a new table row and display a textarea for an explanation. To ensure data validation, I am utilizi ...

How to retrieve the context of a .js file using jQuery $.ajax without automatically executing upon receipt

Upon fetching a *.js file using $.ajax, the scripts are executed upon receipt! Is there a way to fetch and execute it only when desired? Moreover, is there a method to remove these scripts at will? ...

Unveiling the Technique: Adjusting Field Visibility When Dropdown is Altered

I tried to find a solution on Stackoverflow for displaying/hiding a field based on dropdown selection using either jQuery or inline JavaScript. However, I am facing difficulties when implementing this within a table. Let's start with an easy approach ...

Creating a nested tree structure array from a flat array in Node.js

I have an array structure that I need to convert into a tree array using node.js. The current array looks like this: var data= [ { "id1": 1001, "id2": 1002, "id3": 1004, ... } ...

Failure to receive Ajax XML data in success callback

I am struggling to access the book.xml file that is located in the same folder as other files. Everything seems fine, but the ajax function refuses to enter the success state and instead shows an [object object] error message. The XML file is very simple, ...

Could converting a 47-byte JSON string into 340 MB be possible through JSON stringification?

var keys = [7925181,"68113227"]; var vals = {"7925181":["68113227"],"68113227":["7925181"]}; var temp = []; for (var i = 0; i < keys.length; i++) { temp[keys[i]] = vals[keys[i]]; } //alert(JSON.stringify(vals).length); alert(JSON.stringify(temp).le ...

What is the correct way to align labels to the right in a column layout?

I just started learning React JS and I'm using Material-UI. One issue I encountered is that when I use the column layout with an 'xs' value, the component inside the column appears aligned to the left. To align it to the right, I tried incr ...

The callback function in JavaScript is not updating AngularJS unless it is written in shorthand form

Within an angular controller designed for user login functionality, the code snippets below are extracted from an angular-meteor tutorial: this.login = function() { Meteor.loginWithPassword(this.credentials.email, this.credentials.password, (e ...

Encountered an error: "Type error undefined" while attempting to populate a form using AJAX and JSON

Upon inspecting the development console, it's clear that my AJAX request was successful and I've received the necessary JSON data. However, I'm struggling to display it correctly as I keep encountering the error below: Uncaught TypeError: C ...

The JSON array provides the ideal syntax for looping purposes

I am working with JSON data and trying to check if a hovered element matches the names 'sports' or 'technology'. If there is a match, I want to retrieve the corresponding 'text' and 'image' values. However, I am only ...

Sort various divs using a list

I have multiple divs containing different content. On the left side, there is a list of various categories. When a category is clicked, I want to display the corresponding div for that category. Initially, I want the main category to be loaded, with no opt ...

Calculate the length of a JSON array by using the value of one of its

What is the most efficient way to obtain the length of a JSON array in jQuery, based on the value of its attribute? As an illustration, consider the following array: var arr = [{ "name":"amit", "online":true },{ "name":"rohit", "online":f ...