Skip to content

Commit 2a0542e

Browse files
authored
Adding idempotence check in aws-node-express-dynamodb-api/handler.js
This commit uses the idempotence feature of DynamoDB transaction to make the operation of writing username idempotent.
1 parent 8a2a2a3 commit 2a0542e

File tree

1 file changed

+21
-8
lines changed

1 file changed

+21
-8
lines changed

aws-node-express-dynamodb-api/handler.js

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -34,28 +34,41 @@ app.get("/users/:userId", async function (req, res) {
3434
});
3535

3636
app.post("/users", async function (req, res) {
37-
const { userId, name } = req.body;
37+
const { userId, name, token } = req.body;
3838
if (typeof userId !== "string") {
3939
res.status(400).json({ error: '"userId" must be a string' });
4040
} else if (typeof name !== "string") {
4141
res.status(400).json({ error: '"name" must be a string' });
42+
} else if (typeof token !== "string") {
43+
res.status(400).json({ error: '"token" must be a string' });
4244
}
4345

4446
const params = {
45-
TableName: USERS_TABLE,
46-
Item: {
47-
userId: userId,
48-
name: name,
49-
},
47+
// idempotence check
48+
ClientRequestToken: token,
49+
TransactItems: [
50+
{
51+
Update: {
52+
TableName: USERS_TABLE,
53+
Key: { userId: userId },
54+
UpdateExpression: 'set #a = :v',
55+
ExpressionAttributeNames: {'#a' : 'name'},
56+
ExpressionAttributeValues: {
57+
':v': name
58+
}
59+
}
60+
}
61+
]
5062
};
51-
63+
5264
try {
53-
await dynamoDbClient.put(params).promise();
65+
await dynamoDbClient.transactWrite(params).promise();
5466
res.json({ userId, name });
5567
} catch (error) {
5668
console.log(error);
5769
res.status(500).json({ error: "Could not create user" });
5870
}
71+
5972
});
6073

6174
app.use((req, res, next) => {

0 commit comments

Comments
 (0)