@@ -34,28 +34,41 @@ app.get("/users/:userId", async function (req, res) {
3434} ) ;
3535
3636app . 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
6174app . use ( ( req , res , next ) => {
0 commit comments