-
Notifications
You must be signed in to change notification settings - Fork 0
/
routes.js
63 lines (53 loc) · 1.97 KB
/
routes.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
const express = require('express');
const path = require('path');
const Url = require('./db/url-schema.js');
const utils = require('./utils.js');
const router = express.Router();
async function createRoute(res, url, slug) {
try {
if (!utils.isUrlFormatted(url))
return utils.sendBadRequestError(res, 'URL "'+url+'" is malformatted. Must be a valid URL.', 'Malformed URL');
if (!utils.isAlphaNumeric(slug))
return utils.sendBadRequestError(res, 'Slug "'+slug+'" is malformatted. Must be alphanumeric.', 'Malformed Short URL');
slug = slug.toLowerCase();
if (await Url.exists({slug: slug}))
return utils.sendBadRequestError(res, 'Slug "'+slug+'" already exists. Updates are not supported at this time.', 'Already Exists');
await new Url({url, slug}).save();
utils.sendSuccessfulSlugCreation(res, slug);
} catch (err) {
utils.sendInternalServerError(res, err);
}
}
router.get('/', async (req, res) => {
utils.sendFile(res, 'static/index.html');
});
router.post('/', async (req, res) => {
let slug;
do {
slug = utils.generateSlug();
} while (await Url.exists({slug: slug}));
await createRoute(res, req.body.url, slug);
});
router.get('/:slug', async (req, res) => {
try {
const url = await Url.findOne({slug: req.params.slug.toLowerCase()});
if (url)
res.redirect(301, url.url);
else
utils.sendNotFoundError(res);
} catch (err) {
utils.sendInternalServerError(res, err);
}
});
router.put('/:slug', async (req, res) => {
if (!req.params.slug)
return utils.sendBadRequestError(res, 'Cannot PUT to root path.');
await createRoute(res, req.body.url, req.params.slug.toLowerCase());
});
router.get('/*', async (req, res) => {
utils.sendNotFoundError(res);
});
router.all('/*', async (req, res) => {
utils.sendBadRequestError(res, 'Nothing exists at this endpoint.');
});
module.exports = router;