11const AWS = require ( "aws-sdk" ) ;
22const express = require ( "express" ) ;
33const serverless = require ( "serverless-http" ) ;
4-
54const app = express ( ) ;
65
76const USERS_TABLE = process . env . USERS_TABLE ;
87const dynamoDbClient = new AWS . DynamoDB . DocumentClient ( ) ;
98
9+
1010app . use ( express . json ( ) ) ;
1111
1212app . get ( "/users/:userId" , async function ( req , res ) {
@@ -34,18 +34,15 @@ app.get("/users/:userId", async function (req, res) {
3434} ) ;
3535
3636app . 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