File tree Expand file tree Collapse file tree 2 files changed +47
-12
lines changed Expand file tree Collapse file tree 2 files changed +47
-12
lines changed Original file line number Diff line number Diff line change 1
1
2
- let response ;
2
+ const dynamodb = require ( 'aws-sdk/clients/dynamodb' ) ;
3
+ const docClient = new dynamodb . DocumentClient ( ) ;
4
+ const tableName = process . env . DATA_TABLE ;
5
+ const crypto = require ( "crypto" ) ;
6
+
3
7
4
8
exports . lambdaHandler = async ( event , context ) => {
5
- try {
6
- response = {
7
- 'statusCode' : 200 ,
8
- 'body' : JSON . stringify ( {
9
- message : 'save data' ,
10
- // location: ret.data.trim()
11
- } )
12
- }
13
- } catch ( err ) {
14
- console . log ( err ) ;
15
- return err ;
9
+ if ( event . httpMethod !== 'POST' ) {
10
+ throw new Error ( `postMethod only accepts POST method, you tried: ${ event . httpMethod } method.` ) ;
16
11
}
12
+ console . info ( 'table name:' , tableName ) ;
13
+
14
+ const body = JSON . parse ( event . body )
15
+ var params = {
16
+ TableName : tableName ,
17
+ Item : {
18
+ id : crypto . randomBytes ( 16 ) . toString ( "hex" ) ,
19
+ message : body . message ,
20
+ }
21
+ } ;
22
+
23
+ const result = await docClient . put ( params ) . promise ( ) ;
24
+ console . log ( result ) ;
25
+ const response = {
26
+ statusCode : 200 ,
27
+ headers : {
28
+ "Access-Control-Allow-Origin" : "*" ,
29
+ "Access-Control-Allow-Methods" : "OPTIONS,POST"
30
+ } ,
31
+ body : JSON . stringify ( { message : 'saved data' } )
32
+ } ;
33
+
34
+ console . info ( `response from: ${ event . path } statusCode: ${ response . statusCode } body: ${ response . body } ` ) ;
17
35
18
36
return response
19
37
} ;
Original file line number Diff line number Diff line change @@ -48,6 +48,12 @@ Resources:
48
48
FunctionName : !Sub "${AWS::StackName}-saveMyDataFunction"
49
49
CodeUri : src/handlers/save-data/
50
50
Handler : app.lambdaHandler
51
+ Policies :
52
+ - DynamoDBCrudPolicy :
53
+ TableName : !Ref MySimpleTableDB
54
+ Environment :
55
+ Variables :
56
+ DATA_TABLE : !Ref MySimpleTableDB
51
57
Events :
52
58
HelloWorld :
53
59
Type : HttpApi
@@ -56,6 +62,17 @@ Resources:
56
62
Path : /data
57
63
Method : post
58
64
65
+ MySimpleTableDB :
66
+ Type : AWS::Serverless::SimpleTable
67
+ Properties :
68
+ TableName : !Sub "my-data-${Environment}"
69
+ PrimaryKey :
70
+ Name : id
71
+ Type : String
72
+ ProvisionedThroughput :
73
+ ReadCapacityUnits : 2
74
+ WriteCapacityUnits : 2
75
+
59
76
Outputs :
60
77
DataApi :
61
78
Description : " API Gateway endpoint URL for Prod stage for Hello World function"
You can’t perform that action at this time.
0 commit comments