-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
107 lines (88 loc) · 1.97 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
const bodyParser = require('body-parser');
const express = require('express');
const morgan = require('morgan');
const Database = require('@replit/database');
const { customAlphabet } = require('nanoid');
const { readFile } = require('fs').promises;
const db = new Database();
const alphabet =
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
const size = 7;
const nanoid = customAlphabet(alphabet, size);
const idRegex = new RegExp(`^[${alphabet}]{${7}}$`);
const app = express();
app.use(morgan('dev'));
const urlencodedParser = bodyParser.urlencoded({ extended: false });
const html = readFile('index.html');
/**
* GET /
*/
app.get('/', async (req, res) => {
res.set('Content-Type', 'text/html');
res.send(await html);
});
/**
* POST /
*/
app.post('/', urlencodedParser, async (req, res) => {
const { url } = req.body;
res.set('Content-Type', 'text/html');
if (!url) {
res.send(await html);
return;
}
// ensure id is unique
let id;
while (true) {
id = nanoid();
if (!(await db.get(id))) {
await db.set(id, url);
break;
}
}
const shortenedUrl = `${req.get('host')}/${id}`;
const block = `
<p>
Shortened URL:
<a href="${id}" rel="noopener noreferrer" target="_blank">
${shortenedUrl}
</a>
</p>
`;
res.send((await html) + block);
});
/**
* GET /:id
*/
app.get('/:id', async (req, res, next) => {
const { id } = req.params;
if (!idRegex.test(id)) {
return next();
}
const fullUrl = await db.get(id);
if (!fullUrl) {
return next();
}
res.redirect(301, fullUrl);
});
/*
// empty databse (development)
app.get('/db-empty', async (req, res, next) => {
await db.empty();
res.send('Database Emptied');
});
*/
/**
* 404
*/
app.use((req, res) => {
res.status(404).send('Not Found');
});
/**
* Error
*/
app.use((err, req, res, next) => {
next(err);
});
const port = process.env.PORT || 3000;
app.listen(port, () => console.log('Listening on port %d', port));