-
Notifications
You must be signed in to change notification settings - Fork 0
/
fake-email-server.js
50 lines (39 loc) · 1.12 KB
/
fake-email-server.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
const { createServer } = require("http")
function startFakeEmailServer(callback) {
createServer(emailListener).listen(3456, () => {
console.log("MailServer Started on port 3456")
callback()
})
}
async function emailListener(request, response) {
if(request.url !== "/send-email" || request.method !== "POST") {
response.writeHead(404)
response.end("")
return
}
try {
const payload = await bodyFrom(request)
const { recipient, subject, body } = JSON.parse(payload)
if(!recipient || !subject || !body) {
throw Error("payload incomplete")
}
console.log(`Sending email to "${recipient}" with subject "${subject}" and body "${body}"`)
response.end(`Email sent to ${recipient}`)
} catch(e) {
response.writeHead(500)
response.end(e.toString())
}
}
function bodyFrom(request) {
let buffer = []
return new Promise((resolve, reject) => {
request.on('data', (chunk) => {
buffer.push(chunk)
})
request.on('end', () => {
resolve(Buffer.concat(buffer).toString())
})
request.on('error', reject)
})
}
exports.createServer = startFakeEmailServer