Skip to content

Commit 7c5381d

Browse files
committed
feat: Update save-data function
1 parent 73b72c9 commit 7c5381d

File tree

2 files changed

+47
-12
lines changed

2 files changed

+47
-12
lines changed

src/handlers/save-data/app.js

Lines changed: 30 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,37 @@
11

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+
37

48
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.`);
1611
}
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}`);
1735

1836
return response
1937
};

template.yaml

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,12 @@ Resources:
4848
FunctionName: !Sub "${AWS::StackName}-saveMyDataFunction"
4949
CodeUri: src/handlers/save-data/
5050
Handler: app.lambdaHandler
51+
Policies:
52+
- DynamoDBCrudPolicy:
53+
TableName: !Ref MySimpleTableDB
54+
Environment:
55+
Variables:
56+
DATA_TABLE: !Ref MySimpleTableDB
5157
Events:
5258
HelloWorld:
5359
Type: HttpApi
@@ -56,6 +62,17 @@ Resources:
5662
Path: /data
5763
Method: post
5864

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+
5976
Outputs:
6077
DataApi:
6178
Description: "API Gateway endpoint URL for Prod stage for Hello World function"

0 commit comments

Comments
 (0)