-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
95 lines (76 loc) · 1.86 KB
/
main.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
var http = require('http');
var static = require('node-static');
var mailer = require('./mailer');
var file = new static.Server('./public', {
cache: 3600,
indexFile: 'index.html'
});
http.createServer(handler)
.listen(process.env.PORT, '0.0.0.0', function() {
console.log('Static file server listening on port ' + process.env.PORT + '...');
});
function handler(req, res) {
var data = '';
req.addListener('data', function(chunk) {
data += chunk;
});
req.addListener('end', function() {
data = data && JSON.parse(data);
if (req.url === '/contact/submit') {
var errors = validateContact(data);
if (errors.length) {
return sendErrors(res, errors);
}
var mail = {
template: 'contact',
to: '[email protected]',
from: data.name + ' <' + data.email + '>',
subject: 'Contact Form Message',
data: data
};
return mailer.send(mail, function(err) {
if (err) {
return sendErrors(res, err);
}
res.writeHead(200, {'content-type': 'application/json'});
res.end();
});
}
file.serve(req, res, function(err) {
if (err && err.status === 404) {
file.serveFile('/index.html', 200, { }, req, res);
}
});
}).resume();
}
function validateContact(data) {
var errors = [ ];
if (! data.name) {
errors.push('You must enter a name');
}
if (! data.email || data.email.indexOf('@') < 1) {
errors.push('You must enter a valid email address');
}
if (! data.message) {
errors.push('You haven\'t entered a message yet');
}
return errors;
}
function sendErrors(res, errors) {
res.writeHead(500, {
'content-type': 'application/json'
});
errors = (Array.isArray(errors) ? errors : [ errors ]).map(function(err) {
if (err.stack) {
return err.stack;
}
if (err.message) {
return err.message;
}
return err;
});
res.write(JSON.stringify({
errors: errors
}));
res.end();
}