Skip to content

Commit

Permalink
Simplify the idempotence check in handler.js
Browse files Browse the repository at this point in the history
Now the client does not need to provide a token. The requestId provided by AWS can be used as the ClientRequestToken.
  • Loading branch information
Nsupyq authored Nov 3, 2021
1 parent 3d76b88 commit 4cf7fed
Showing 1 changed file with 9 additions and 8 deletions.
17 changes: 9 additions & 8 deletions aws-node-express-dynamodb-api/handler.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
const AWS = require("aws-sdk");
const express = require("express");
const serverless = require("serverless-http");

const app = express();

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


app.use(express.json());

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

app.post("/users", async function (req, res) {
const { userId, name, token } = req.body;
const { userId, name } = req.body;
if (typeof userId !== "string") {
res.status(400).json({ error: '"userId" must be a string' });
} else if (typeof name !== "string") {
res.status(400).json({ error: '"name" must be a string' });
} else if (typeof token !== "string") {
res.status(400).json({ error: '"token" must be a string' });
}

const params = {
// idempotence check
ClientRequestToken: token,
ClientRequestToken: req.context.awsRequestId,
TransactItems: [
{
Update: {
Expand All @@ -61,7 +58,7 @@ app.post("/users", async function (req, res) {
]
};

try {
try{
await dynamoDbClient.transactWrite(params).promise();
res.json({ userId, name });
} catch (error) {
Expand All @@ -78,4 +75,8 @@ app.use((req, res, next) => {
});


module.exports.handler = serverless(app);
module.exports.handler = serverless(app,{
request:(req,event,context)=>{
req.context=context
}
});

0 comments on commit 4cf7fed

Please sign in to comment.