AWS Security ChangesHomeSearch

AWS code-library documentation change

Service: code-library · 2025-04-11 · Documentation low

File: code-library/latest/ug/javascript_3_dynamodb_code_examples.md

Summary

Added dynamic filter expression construction example

Security assessment

Shows safe parameter handling but doesn't directly address security vulnerabilities

Diff

diff --git a/code-library/latest/ug/javascript_3_dynamodb_code_examples.md b/code-library/latest/ug/javascript_3_dynamodb_code_examples.md
index 3ef5793de..9ba23d1b4 100644
--- a//code-library/latest/ug/javascript_3_dynamodb_code_examples.md
+++ b//code-library/latest/ug/javascript_3_dynamodb_code_examples.md
@@ -1074,5 +1074 @@ The following code example shows how to use `Query`.
-  * Use the begins_with function in a key condition expression.
-
-  * Filter items based on a prefix pattern in the sort key.
-
-
+**SDK for JavaScript (v3)**
@@ -1081 +1077 @@ The following code example shows how to use `Query`.
-**SDK for JavaScript (v3)**
+###### Note
@@ -1082,0 +1079 @@ The following code example shows how to use `Query`.
+There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples). 
@@ -1084 +1081 @@ The following code example shows how to use `Query`.
-Query a DynamoDB table using a begins_with condition on the sort key with AWS SDK for JavaScript.
+This example uses the document client to simplify working with items in DynamoDB. For API details see [QueryCommand](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-lib-dynamodb/Class/QueryCommand/).
@@ -1087 +1084,2 @@ Query a DynamoDB table using a begins_with condition on the sort key with AWS SD
-    const { DynamoDBClient, QueryCommand } = require("@aws-sdk/client-dynamodb");
+    import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
+    import { QueryCommand, DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb";
@@ -1089,22 +1087,2 @@ Query a DynamoDB table using a begins_with condition on the sort key with AWS SD
-    /**
-     * Queries a DynamoDB table for items where the sort key begins with a specific prefix
-     * 
-     * @param {Object} config - AWS SDK configuration object
-     * @param {string} tableName - The name of the DynamoDB table
-     * @param {string} partitionKeyName - The name of the partition key
-     * @param {string} partitionKeyValue - The value of the partition key
-     * @param {string} sortKeyName - The name of the sort key
-     * @param {string} prefix - The prefix to match at the beginning of the sort key
-     * @returns {Promise<Object>} - The query response
-     */
-    async function queryWithBeginsWith(
-      config,
-      tableName,
-      partitionKeyName,
-      partitionKeyValue,
-      sortKeyName,
-      prefix
-    ) {
-      try {
-        // Create DynamoDB client
-        const client = new DynamoDBClient(config);
+    const client = new DynamoDBClient({});
+    const docClient = DynamoDBDocumentClient.from(client);
@@ -1112,8 +1090,5 @@ Query a DynamoDB table using a begins_with condition on the sort key with AWS SD
-        // Construct the query input
-        const input = {
-          TableName: tableName,
-          KeyConditionExpression: "#pk = :pkValue AND begins_with(#sk, :prefix)",
-          ExpressionAttributeNames: {
-            "#pk": partitionKeyName,
-            "#sk": sortKeyName
-          },
+    export const main = async () => {
+      const command = new QueryCommand({
+        TableName: "CoffeeCrop",
+        KeyConditionExpression:
+          "OriginCountry = :originCountry AND RoastDate > :roastDate",
@@ -1121,3 +1096,9 @@ Query a DynamoDB table using a begins_with condition on the sort key with AWS SD
-            ":pkValue": { S: partitionKeyValue },
-            ":prefix": { S: prefix }
-          }
+          ":originCountry": "Ethiopia",
+          ":roastDate": "2023-05-01",
+        },
+        ConsistentRead: true,
+      });
+    
+      const response = await docClient.send(command);
+      console.log(response);
+      return response;
@@ -1126,8 +1106,0 @@ Query a DynamoDB table using a begins_with condition on the sort key with AWS SD
-        // Execute the query
-        const command = new QueryCommand(input);
-        return await client.send(command);
-      } catch (error) {
-        console.error(`Error querying with begins_with: ${error}`);
-        throw error;
-      }
-    }
@@ -1135,0 +1109 @@ Query a DynamoDB table using a begins_with condition on the sort key with AWS SD
+  * For more information, see [AWS SDK for JavaScript Developer Guide](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/dynamodb-example-query-scan.html#dynamodb-example-table-query-scan-querying). 
@@ -2354,0 +2329,73 @@ Query with complex filters using AWS SDK for JavaScript.
+Query with a dynamically constructed filter expression using AWS SDK for JavaScript.
+    
+    
+    const { DynamoDBClient, QueryCommand } = require("@aws-sdk/client-dynamodb");
+    
+    async function queryWithDynamicFilter(
+      config,
+      tableName,
+      partitionKeyName,
+      partitionKeyValue,
+      sortKeyName,
+      sortKeyValue,
+      filterParams = {}
+    ) {
+      try {
+        // Create DynamoDB client
+        const client = new DynamoDBClient(config);
+    
+        // Initialize filter expression components
+        let filterExpressions = [];
+        const expressionAttributeValues = {
+          ":pkValue": { S: partitionKeyValue },
+          ":skValue": { S: sortKeyValue }
+        };
+        const expressionAttributeNames = {
+          "#pk": partitionKeyName,
+          "#sk": sortKeyName
+        };
+    
+        // Add status filter if provided
+        if (filterParams.status) {
+          filterExpressions.push("status = :status");
+          expressionAttributeValues[":status"] = { S: filterParams.status };
+        }
+    
+        // Add minimum views filter if provided
+        if (filterParams.minViews !== undefined) {
+          filterExpressions.push("views >= :minViews");
+          expressionAttributeValues[":minViews"] = { N: filterParams.minViews.toString() };
+        }
+    
+        // Add author filter if provided
+        if (filterParams.author) {
+          filterExpressions.push("author = :author");
+          expressionAttributeValues[":author"] = { S: filterParams.author };
+        }
+    
+        // Construct the query input
+        const input = {
+          TableName: tableName,
+          KeyConditionExpression: "#pk = :pkValue AND #sk = :skValue"
+        };
+    
+        // Add filter expression if any filters were provided
+        if (filterExpressions.length > 0) {
+          input.FilterExpression = filterExpressions.join(" AND ");
+        }
+    
+        // Add expression attribute names and values
+        input.ExpressionAttributeNames = expressionAttributeNames;
+        input.ExpressionAttributeValues = expressionAttributeValues;
+    
+        // Execute the query
+        const command = new QueryCommand(input);
+        return await client.send(command);
+      } catch (error) {
+        console.error(`Error querying with dynamic filter: ${error}`);
+        throw error;
+      }
+    }
+    
+    
+
@@ -2766 +2813,10 @@ Execute single PartiQL statements.
-The following code example shows how to query data using PartiQL SELECT statements.
+The following code example shows how to query a table using a Global Secondary Index.
+
+  * Query a DynamoDB table using its primary key.
+
+  * Query a Global Secondary Index (GSI) for alternate access patterns.
+
+  * Compare table queries and GSI queries.
+
+
+
@@ -2771 +2827 @@ The following code example shows how to query data using PartiQL SELECT statemen
-Query items from a DynamoDB table using PartiQL SELECT statements with AWS SDK for JavaScript.
+Query a DynamoDB table using the primary key with AWS SDK for JavaScript.
@@ -2774,10 +2830 @@ Query items from a DynamoDB table using PartiQL SELECT statements with AWS SDK f
-    /**
-     * This example demonstrates how to query items from a DynamoDB table using PartiQL.
-     * It shows different ways to select data with various index types.
-     */
-    import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
-    import {
-      DynamoDBDocumentClient,
-      ExecuteStatementCommand,
-      BatchExecuteStatementCommand,
-    } from "@aws-sdk/lib-dynamodb";
+    const { DynamoDBClient, QueryCommand } = require("@aws-sdk/client-dynamodb");
@@ -2786,2 +2833 @@ Query items from a DynamoDB table using PartiQL SELECT statements with AWS SDK f
-     * Select all items from a DynamoDB table using PartiQL.
-     * Note: This should be used with caution on large tables.
+     * Queries a DynamoDB table using the primary key
@@ -2789,2 +2835,4 @@ Query items from a DynamoDB table using PartiQL SELECT statements with AWS SDK f
-     * @param tableName - The name of the DynamoDB table
-     * @returns The response from the ExecuteStatementCommand
+     * @param {Object} config - AWS SDK configuration object
+     * @param {string} tableName - The name of the DynamoDB table
+     * @param {string} userId - The user ID to query by (partition key)
+     * @returns {Promise<Object>} - The query response
@@ -2792,3 +2840,8 @@ Query items from a DynamoDB table using PartiQL SELECT statements with AWS SDK f
-    export const selectAllItems = async (tableName: string) => {