-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
86 lines (71 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
const express = require('express');
const cors = require('cors');
const path = require('path');
const compression = require('compression');
const enforce = require('express-sslify');
// Email API
const sgMail = require('@sendgrid/mail');
if (process.env.NODE_ENV !== 'production') require('dotenv').config();
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const app = express();
const port = process.env.PORT || 5000;
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors());
if (process.env.NODE_ENV === 'production') {
app.use(enforce.HTTPS({ trustProtoHeader: true }));
app.use(express.static(path.join(__dirname, 'client/build')));
app.use(compression());
app.get('*', function (req, res) {
res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
});
}
app.get('/service-worker.js', (req, res) => {
res.sendFile(path.resolve(__dirname, '..', 'build', 'service-worker.js'));
});
app.post('/payment', (req, res) => {
const { token, amount } = req.body;
const body = {
source: token.id,
amount: amount,
currency: 'usd'
};
stripe.charges.create(body, (stripeErr, stripeRes) => {
if (stripeErr) {
res.status(500).send({ error: stripeErr });
}
else {
res.status(200).send({ success: stripeRes });
}
});
});
app.post('/contact', async (req, res) => {
const { name, email, message } = req.body;
const msg = {
to: '[email protected]',
from: email,
subject: `CRWN CLOTHING contact message from: ${name}`,
text: message
};
if (/(.+)@(.+){2,}\.(.+){2,}/.test(email)) {
if (email == '' && message == '')
res.status(422).json('Fill all inputs first');
try {
await sgMail.send(msg);
res.status(200).send({ response: 'Email successfully sent' });
} catch (error) {
if (error.response) {
console.error(error.response.body);
res.status(400).send({ response: error.response.body });
}
}
}
else {
res.status(422).json('Email address format should look like this: [email protected]');
}
});
app.listen(port, error => {
if (error) throw error;
console.log('Server runing on port ' + port);
});