Skip to content

Commit e3cbbbd

Browse files
authored
Simplify the idempotence check in handler.js
Now the client does not need to provide a token. The requestId provided by AWS can be used as the ClientRequestToken.
1 parent 2a0542e commit e3cbbbd

File tree

1 file changed

+9
-8
lines changed

1 file changed

+9
-8
lines changed

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

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
const AWS = require("aws-sdk");
22
const express = require("express");
33
const serverless = require("serverless-http");
4-
54
const app = express();
65

76
const USERS_TABLE = process.env.USERS_TABLE;
87
const dynamoDbClient = new AWS.DynamoDB.DocumentClient();
98

9+
1010
app.use(express.json());
1111

1212
app.get("/users/:userId", async function (req, res) {
@@ -34,18 +34,15 @@ app.get("/users/:userId", async function (req, res) {
3434
});
3535

3636
app.post("/users", async function (req, res) {
37-
const { userId, name, token } = req.body;
37+
const { userId, name } = 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' });
4442
}
4543

4644
const params = {
47-
// idempotence check
48-
ClientRequestToken: token,
45+
ClientRequestToken: req.context.awsRequestId,
4946
TransactItems: [
5047
{
5148
Update: {
@@ -61,7 +58,7 @@ app.post("/users", async function (req, res) {
6158
]
6259
};
6360

64-
try {
61+
try{
6562
await dynamoDbClient.transactWrite(params).promise();
6663
res.json({ userId, name });
6764
} catch (error) {
@@ -78,4 +75,8 @@ app.use((req, res, next) => {
7875
});
7976

8077

81-
module.exports.handler = serverless(app);
78+
module.exports.handler = serverless(app,{
79+
request:(req,event,context)=>{
80+
req.context=context
81+
}
82+
});

0 commit comments

Comments
 (0)