Search code examples
aws-lambdaamazon-dynamodb

How to do a dynamoDB.scan() from Lambda


I am teaching myself Lambda and AWS services. I am simply trying to access everything in the APIGateway table called "Vocabulary" but I am following a tutorial that is not compatible with ES5 and according to the error I got earlier, it didnt like require for importing aws-sdk, but to change it to import instead.

I'm using my best knowledge in JS to go along with this but I'm hitting deadends everywhere.

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

const docClient = new DynamoDBClient({});

export const handler = async function(event, context, callback) {

  let scanningParameters = {
    TableName : 'Vocabulary'
  };

  docClient.scan(scanningParameters, 
      function(err, data){
          if (err) {
              callback(err, null);
          } else {
              callback(null, data.Items);
          }
      });
  };

The error I'm getting is

Response
{
  "errorType": "TypeError",
  "errorMessage": "docClient.scan is not a function",
  "trace": [
    "TypeError: docClient.scan is not a function",
    "    at Runtime.handler (file:///var/task/index.mjs:11:13)",
    "    at Runtime.handleOnceNonStreaming (file:///var/runtime/index.mjs:1147:29)"
  ]
}

Thanks (Keep in mind, I know very little about all of this still)


Solution

  • Using Lambda with node runtime 18 you need to use the JS SDK V3, which has a syntax like the following, note it's a send command which is generic for all APIs.

    import { DynamoDBClient, ScanCommand } from "@aws-sdk/client-dynamodb";
    
    const client = new DynamoDBClient({});
    
    export const handler = async function(event, context, callback) {
      
    const command = new ScanCommand({
        TableName: "Vocabulary",
      });
    
      const response = await client.send(command);
    
      response.Items.forEach(function (item) {
        console.log(`${item}`);
      });
      return response;
    };