-
Notifications
You must be signed in to change notification settings - Fork 0
/
lambda.js
77 lines (73 loc) · 2.52 KB
/
lambda.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'});
const tableName = "email-subscribers";
const emailRegex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i;
exports.handler = (event, context, callback) => {
const headers = {
'Content-Type': 'application/json',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Origin': '*'
};
const defaultResponse = {
"headers": headers,
"isBase64Encoded": false,
};
switch (event.httpMethod) {
case "OPTIONS":
const response = {
"statusCode": 200,
...defaultResponse,
};
callback(null, response);
break;
case "POST": {
const body = JSON.parse(event.body);
if (!emailRegex.test(body.email)) {
const responseBody = { error: "Invalid email" };
const response = {
statusCode: 400,
body: JSON.stringify(responseBody),
...defaultResponse,
};
callback(null, response);
break;
}
dynamodb.putItem({
TableName: tableName,
Item : {
"email": {S: body.email },
}
}, function(err, data) {
if (err) {
console.error('putting item into dynamodb failed: '+err);
const responseBody = { error: "Server error" };
const response = {
"statusCode": 500,
body: JSON.stringify(responseBody),
...defaultResponse,
};
callback(null, response);
}
else {
console.log('successfully put item into dybamodb');
const responseBody = { email: body.email };
const response = {
"statusCode": 201,
body: JSON.stringify(responseBody),
...defaultResponse,
};
callback(null, response);
}
});
break;
}
default: {
console.error('unsupported method' + event.httpMethod);
const response = {
"statusCode": 405,
...defaultResponse,
};
callback(null, response);
}
}
};