-
Notifications
You must be signed in to change notification settings - Fork 220
/
Copy pathput-item-conditional.js
40 lines (37 loc) · 1.5 KB
/
put-item-conditional.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/* This is an example of a simple PutCommand with a ConditionExpression using
the higher level DocumentClient for Amazon DynamoDB. The conditional
expression must be true for this Put call to succeed. */
const { DynamoDBClient } = require("@aws-sdk/client-dynamodb");
const { DynamoDBDocumentClient, PutCommand } = require("@aws-sdk/lib-dynamodb");
async function putItems() {
const client = new DynamoDBClient({ region: "us-west-2" });
const ddbDocClient = DynamoDBDocumentClient.from(client);
return await ddbDocClient.send(
new PutCommand({
TableName: "RetailDatabase",
Item: {
pk: "[email protected]", // Partition key
sk: "metadata", // Sort key
name: "Jim Roberts",
first_name: "Jim",
last_name: "Roberts",
address: {
road: "456 Nowhere Lane",
city: "Langely",
state: "WA",
pcode: "98260",
country: "USA",
},
username: "jrob",
},
// Start conditional expression to make sure the value of the sk attribute begins with the string "meta".
// If not, then the put will fail with a "ConditionalCheckFailedException"
ConditionExpression: "begins_with(sk, :val)",
ExpressionAttributeValues: {":val" : "meta"}
})
);
}
putItems()
.then((data) =>
console.log("PutCommand succeeded:", JSON.stringify(data, null, 2)))
.catch((error) => console.error(JSON.stringify(error, null, 2)));