-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
67 lines (60 loc) · 1.69 KB
/
index.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
const ApiBuilder = require('claudia-api-builder');
const querystring = require('querystring');
const AWS = require('aws-sdk');
const shortid = require('shortid');
const api = new ApiBuilder();
const dynamoDb = new AWS.DynamoDB.DocumentClient();
module.exports = api;
api.post('/contact', (request) => {
'use strict';
const nodemailer = require('nodemailer');
const transporter = nodemailer.createTransport({
service: 'Mailgun',
port: 465,
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASSWORD
}
});
let text = "";
const body = querystring.parse(request.body);
Object.keys(body).forEach((key) => {
text += key + ": " + body[key] + "\n";
});
const mailOptions = {
from: process.env.EMAIL_USER, // sender address
to: process.env.EMAIL_ADDRESS,
subject: 'New contact form submission', // Subject line
text // plaintext body
}
const time = new Date();
const id = shortid.generate();
const params = {
TableName: 'contact',
Item: {
id,
email: body.email,
name: body.name === '' ? null : body.name,
location: body.location === '' ? null : body.location,
phone: body.phone === '' ? null : body.phone,
message: body.message === '' ? null : body.message,
time: time.toString(),
}
};
return transporter.sendMail(mailOptions)
.then(function () {
var dynamoPromise = dynamoDb.put(params).promise()
return dynamoPromise.then(function (response) {
return;
})
.catch(function (error) {
throw error;
})
})
.then(function() {
return new api.ApiResponse('OK', {'Content-Type': 'text/plain'}, 200);
})
.catch(function (error) {
return new api.ApiResponse({ error }, {'Content-Type': 'text/plain'}, 400);
});
});