-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
160 lines (147 loc) · 3.86 KB
/
index.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
const path = require('path');
const express = require('express');
const morgan = require('morgan');
const helmet = require('helmet');
const yup = require('yup');
const monk = require('monk');
const rateLimit = require('express-rate-limit');
const slowDown = require('express-slow-down');
const cors = require('cors');
const { nanoid } = require('nanoid');
require('dotenv').config({
path: './.env',
});
const port = process.env.PORT || '2550';
const urlHost = process.env.URLHOST || 'localhost';
const node_Mode = process.env.NODE_ENV || 'development';
const mongoURI = process.env.MONGODB_URI || 'mongodb://localhost:27017/shrtnr';
const db = monk(mongoURI);
const urls = db.get('urls');
urls.createIndex({ slug: 1 }, { unique: true });
const app = express();
app.enable('trust proxy');
app.use(cors());
app.use(helmet());
app.use(morgan('common'));
app.use(express.json());
app.use(express.static('./public'));
const notFoundPath = path.join(__dirname, 'public/404.html');
app.get('/:id', async (req, res, next) => {
const { id: slug } = req.params;
try {
const url = await urls.findOne({
slug,
});
if (url) {
return res.redirect(url.url);
}
return res.status(404).sendFile(notFoundPath);
} catch (error) {
return res.status(404).sendFile(notFoundPath);
}
});
const schema = yup.object().shape({
slug: yup
.string()
.trim()
.matches(/^[\w\-]+$/i),
url: yup.string().trim().url().required(),
});
app.post(
'/url',
slowDown({
windowMs: 10 * 1000,
delayAfter: 1,
delayMs: 500,
}),
rateLimit({
windowMs: 10 * 100,
max: 3,
}),
async (req, res, next) => {
const getAgent = req.headers['user-agent'];
if (getAgent.includes('curl')) {
setAgent = 'consoleClient';
} else if (getAgent.includes('wget')) {
setAgent = 'consoleClient';
} else if (getAgent.includes('httpie')) {
setAgent = 'consoleClient';
}
let { slug, url } = req.body;
try {
await schema.validate({
slug,
url,
});
if (url.includes(urlHost)) {
throw new Error(`Error: Adding ${urlHost} is not supported. 🛑`);
}
if (!slug) {
slug = nanoid(5);
} else {
const existing = await urls.findOne({
slug,
});
if (existing) {
throw new Error(`Slug http://${urlHost}/${slug} is in use. 🍔`);
}
}
slug = slug.toLowerCase();
const newUrl = {
url,
slug,
};
const created = await urls.insert(newUrl);
if (!setAgent) {
res.status(200).json(created);
} else {
res.status(200).send(`http://${urlHost}/${slug}` + '\n');
}
} catch (error) {
next(error);
}
}
);
app.use((req, res, next) => {
const getAgent = req.headers['user-agent'];
if (getAgent.includes('curl')) {
setAgent = 'consoleClient';
} else if (getAgent.includes('wget')) {
setAgent = 'consoleClient';
} else if (getAgent.includes('httpie')) {
setAgent = 'consoleClient';
}
if (setAgent) {
res.status(404).send('File not found 😠');
} else {
res.status(404).sendFile(notFoundPath);
}
});
app.use((error, req, res, next) => {
const getAgent = req.headers['user-agent'];
if (getAgent.includes('curl')) {
setAgent = 'consoleClient';
} else if (getAgent.includes('wget')) {
setAgent = 'consoleClient';
} else if (getAgent.includes('httpie')) {
setAgent = 'consoleClient';
}
if (error.status) {
res.status(error.status);
} else {
res.status(500);
}
if (setAgent) {
const message = error.message;
res.send(message + '\n');
} else {
res.json({
message: error.message,
stack: process.env.NODE_ENV === 'production' ? '🥞' : error.stack,
});
}
});
app.listen(port, () => {
console.log(`Connected to ${mongoURI}`);
console.log(`Listening on ${port} in ${node_Mode} mode`);
});