forked from persian-developers-hub/nodejs-url-shortener
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
113 lines (101 loc) · 2.48 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
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 { nanoid } = require("nanoid");
require("dotenv").config();
const db = monk(process.env.MONGODB_URI);
const urls = db.get("urls");
urls.createIndex({ slug: 1 }, { unique: true });
const app = express();
app.enable("trust proxy");
app.use(helmet());
app.use(morgan("common"));
app.use(express.json());
app.use(express.static("./public"));
const notFoundPath = path.join(__dirname, "public/404.html");
const schema = yup.object().shape({
slug: yup
.string()
.trim()
.matches(/^[\w\-]+$/i),
url: yup.string().trim().url().required(),
});
// TODO: make this better
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);
}
});
// TODO: Improve performance
app.post(
"/url",
slowDown({
windowMs: 30 * 1000,
delayAfter: 1,
delayMs: 500,
}),
rateLimit({
windowMs: 30 * 1000,
max: 1,
}),
async (req, res, next) => {
let { slug, url } = req.body;
try {
await schema.validate({
slug,
url,
});
// TODO: handle error when use base url
// if (url.includes('')) {
// throw new Error('Stop it. 🛑');
// }
if (!slug) {
slug = nanoid(5);
} else {
const existing = await urls.findOne({ slug });
if (existing) {
throw new Error("Slug in use. 🍔");
}
}
slug = slug.toLowerCase();
const newUrl = {
url,
slug,
};
const created = await urls.insert(newUrl);
res.json(created);
} catch (error) {
next(error);
}
}
);
app.use((req, res, next) => {
res.status(404).sendFile(notFoundPath);
});
app.use((error, req, res, next) => {
if (error.status) {
res.status(error.status);
} else {
res.status(500);
}
res.json({
message: error.message,
stack: process.env.NODE_ENV === "production" ? "🥞" : error.stack,
});
});
const port = process.env.PORT || 1337;
app.listen(port, () => {
console.log(`Listening at http://localhost:${port}`);
});