-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathlambdaHandlers.js
110 lines (96 loc) · 3.04 KB
/
lambdaHandlers.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
const EmailServices = require('./EmailServices')
/**
* Base response HTTP headers
*/
const responseHeaders = {
'Content-Type':'application/json',
'Access-Control-Allow-Origin' : '*', // Required for CORS support to work
'Access-Control-Allow-Credentials' : true // Required for cookies, authorization headers with HTTPS
}
/**
* HTTP response templates
*/
const responses = {
success: (data={}, code=200) => {
return {
'statusCode': code,
'headers': responseHeaders,
'body': JSON.stringify(data)
}
},
error: (error) => {
return {
'statusCode': error.code || 500,
'headers': responseHeaders,
'body': JSON.stringify(error)
}
}
}
/**
* Initialises the EmailServices based on environment variables
*/
function createEmailServices() {
const emailServices = new EmailServices(
process.env.EMAIL_POP3_HOST,
process.env.EMAIL_POP3_USERNAME,
process.env.EMAIL_POP3_PASSWORD,
process.env.EMAIL_POP3_PORT,
process.env.EMAIL_POP3_TLS=="true",
process.env.EMAIL_SMTP_HOST,
process.env.EMAIL_SMTP_USERNAME,
process.env.EMAIL_SMTP_PASSWORD,
process.env.EMAIL_SMTP_PORT,
process.env.EMAIL_SMTP_TLS=="true"
)
return emailServices
}
/**
* These functions are used to handle in incoming Lambda event and process
* it using the relevant services.
*/
module.exports = {
getEmails : (event, context, callback) => {
context.callbackWaitsForEmptyEventLoop = false
const emailServices = createEmailServices()
emailServices.getEmails()
.then(emails => {
callback(null, responses.success(emails))
})
.catch(error => {
callback(null, responses.error(error))
})
},
getEmail : (event, context, callback) => {
context.callbackWaitsForEmptyEventLoop = false
const emailServices = createEmailServices()
// Get the index parameter out of the event
const index = event.pathParameters.index
emailServices.getEmail(index)
.then(email => {
// Create a 'success' response object containing the e-mail we got
// back from emailServices.getEmail()
callback(null, responses.success(email))
})
.catch(error => {
callback(null, responses.error(error))
})
},
sendEmail : (event, context, callback) => {
context.callbackWaitsForEmptyEventLoop = false
// Get and parse the body of the POST request
const requestBody = JSON.parse(event.body)
const emailServices = createEmailServices()
emailServices.sendEmail(
requestBody.from,
requestBody.to,
requestBody.subject,
requestBody.body
)
.then((info) => {
callback(null, responses.success(info))
})
.catch(error => {
callback(null, responses.error(error))
})
}
}