-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathserver.js
93 lines (83 loc) · 2.06 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
91
92
93
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config();
}
const express = require('express');
const app = express();
const URL = require('./models/URL');
const shortid = require('shortid');
const connectDB = require('./config/db');
const cors = require('cors');
const path = require('path');
// Database Connect
connectDB();
// Body Parser Setup
app.use(express.urlencoded({ extended: true }));
app.use(express.json({ extended: true }));
app.set('view engine', 'ejs');
// Security
app.use(cors());
// Middleware Setup
app.use((req, res, next) => {
req.baseUrl = `${req.protocol}://${req.get('host')}`;
next();
});
// Create Short URL
app.post('/api/v2/shorten', async (req, res) => {
try {
const { longURL } = req.body;
console.log(longURL);
let url = await URL.findOne({ longURL });
if (url) {
return res.status(200).json({
...url._doc,
shortURL: `${req.baseUrl}/${url.shortID}`,
});
}
url = await URL.create({
longURL,
shortID: shortid.generate(),
});
res.status(200).json({
...url._doc,
shortURL: `${req.baseUrl}/${url.shortID}`,
});
} catch (e) {
console.log(e);
return res.status(500).json({
msg: 'Server Error',
});
}
});
// Clicks on ShortURLs
app.get('/:shortID', async (req, res) => {
try {
const { shortID } = req.params;
let url = await URL.findOne({ shortID });
if (!url) {
return res.status(404).json({
msg: 'No valid URLs found.',
});
}
url.clicks++;
await url.save();
res.redirect(url.longURL);
} catch (e) {
console.log(e);
res.status(500).json({
msg: 'Server Error',
});
}
});
// Serve static assets in Production
if (process.env.NODE_ENV === 'production') {
// set Static Folder
app.use(express.static('client/build'));
app.get('*', (req, res) =>
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'))
);
}
// Server PORT Setup
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`);
});