-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
90 lines (73 loc) · 2.38 KB
/
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
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
'use strict';
/* eslint camelcase: "off" */
const express = require('express');
const bodyParser = require('body-parser');
const winston = require('winston');
const expressWinston = require('express-winston');
const { getRecentBrochures } = require('./services/mongo-service');
const {
addNewSubscription,
addRecipientToSubscriptionList,
sendConfirmationEmail
} = require('./services/sendgrid-service');
const app = express();
app.set('view engine', 'pug');
app.set('views', './views');
app.use(bodyParser.urlencoded({ extended: true }));
if (process.env.ENVIRONMENT !== 'TEST') {
app.use(expressWinston.logger({
transports: [
new winston.transports.Console({
json: true
})
],
meta: true,
colorize: true,
msg: '{{res.statusCode}} {{req.method}} {{req.url}}'
}));
}
app.use(express.static('public'));
app.get('/', (req, res) => {
return getRecentBrochures()
.then(brochures => res.render('index', { brochures, date_added: brochures.concat().shift().date_added }))
.catch(err => res.send(err));
});
app.post('/newsletter/sub', validatePayloadOrQueryParams, (req, res) => {
return addNewSubscription(req.body.email)
.then(response => addRecipientToSubscriptionList(response.body.persisted_recipients))
.then(() => getRecentBrochures())
.then(brochures => sendConfirmationEmail(req.body.email, brochures))
.then(() => res.redirect('/thank-you'))
.catch(err => {
console.error('error saving new subscription email ', err);
res.status(500);
});
});
app.get('/why', (req, res) => {
return res.render('why');
});
app.get('/thank-you', (req, res) => {
return res.render('thank-you');
});
app.get('/newsletter/welcome-email', (req, res) => {
return getRecentBrochures()
.then(brochures => res.render('newsletter/welcome-email', { brochures, date_added: brochures.concat().shift().date_added }))
.catch(err => res.send(err));
});
app.use(expressWinston.errorLogger({
transports: [
new winston.transports.Console({
json: true,
colorize: true
})
]
}));
function validatePayloadOrQueryParams(req, res, next) {
if (req.method === 'POST' && !{}.hasOwnProperty.call(req.body, 'email')) {
return res.status(422).send('nope.');
} else if (req.method === 'GET' && !{}.hasOwnProperty.call(req.query, 'email')) {
return res.status(422).send('nope.');
}
return next();
}
module.exports = app;