-
Notifications
You must be signed in to change notification settings - Fork 0
/
routes.js
executable file
·74 lines (63 loc) · 1.56 KB
/
routes.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
const express = require('express');
const { createTransport } = require('nodemailer');
const { Message, Feelings } = require('./models');
const logger = require('./utils/logger');
const POST_FUNCTION = {
message: sendEmail,
feelings: saveFeelings
};
function saveAndRespond(obj, res) {
obj.save().then((saved) => {
res.status(200).send({
success: true,
data: `${saved}`
});
}).catch((err) => {
res.status(500).send({
success: false,
data: `${err}`
});
});
}
function apiOk(api) {
return (req, res) => {
res.status(200).send({
success: true,
data: `/${api} OK`
});
};
}
function route(app, endpoint) {
const router = express.Router();
app.use(`/${endpoint}`, router);
router.get('/', apiOk(endpoint));
router.post('/', POST_FUNCTION[endpoint]);
}
function saveFeelings(req, res) {
saveAndRespond(new Feelings(req.body), res);
}
function sendEmail(req, res) {
const smtpTransport = createTransport({
host: 'mail.smtp2go.com',
port: process.env.E_PRT,
auth: {
user: process.env.E_USR,
pass: process.env.E_PSW
}
});
const mailOptions = {
from: process.env.E_SND,
to: process.env.E_REC,
replyTo: `${req.body.email}`,
subject: '[THE-HAPPY-APP] contact',
text: `${req.body.message}`
};
smtpTransport.sendMail(mailOptions, (error) => {
if(error) logger.error(error);
saveAndRespond(new Message(req.body), res);
});
}
function setupRoutes(app) {
Object.keys(POST_FUNCTION).forEach(e => route(app, e));
}
module.exports = { setupRoutes };