@@ -34,28 +34,41 @@ app.get("/users/:userId", async function (req, res) {
34
34
} ) ;
35
35
36
36
app . post ( "/users" , async function ( req , res ) {
37
- const { userId, name } = req . body ;
37
+ const { userId, name, token } = req . body ;
38
38
if ( typeof userId !== "string" ) {
39
39
res . status ( 400 ) . json ( { error : '"userId" must be a string' } ) ;
40
40
} else if ( typeof name !== "string" ) {
41
41
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' } ) ;
42
44
}
43
45
44
46
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
+ ]
50
62
} ;
51
-
63
+
52
64
try {
53
- await dynamoDbClient . put ( params ) . promise ( ) ;
65
+ await dynamoDbClient . transactWrite ( params ) . promise ( ) ;
54
66
res . json ( { userId, name } ) ;
55
67
} catch ( error ) {
56
68
console . log ( error ) ;
57
69
res . status ( 500 ) . json ( { error : "Could not create user" } ) ;
58
70
}
71
+
59
72
} ) ;
60
73
61
74
app . use ( ( req , res , next ) => {
0 commit comments