-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
executable file
·97 lines (66 loc) · 1.5 KB
/
app.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
import { saveUrl, hasSlug, getUrl, incrementUrl } from './lib/db';
import * as log from './lib/log';
import server from './lib/server';
import { route } from './lib/server';
/**
* Config.
*/
const DRY_RUN = false;
const REDIRECT_STATUS = 303;
/**
* Route RegExps.
*/
const REGEX_GET = /^\/([a-zA-Z0-9]+)$/;
const REGEX_CATCHALL = /.*/;
/**
* Set at boot time.
*/
let REGEX_CREATE, DEFAULT, PREFIX;
/**
* Boot the app.
*/
export default function boot({ host, defaultRedirection, create }) {
PREFIX = host ? `http://${host}/` : '';
DEFAULT = defaultRedirection;
REGEX_CREATE = new RegExp(`^/${create}(?::([^\/]+))?/(.+)$`);
route(REGEX_CREATE, createUrlHandler);
route(REGEX_GET, getUrlHandler);
route(REGEX_CATCHALL, catchallHandler);
return server;
}
/**
* Create a new URL.
*/
function createUrlHandler([ , slug, url], req, res) {
slug = saveUrl(url, slug);
res.end(`${PREFIX}${slug}`);
log.create(req, slug);
}
/**
* Try to retireve a URL.
*/
function getUrlHandler([ , slug], req, res) {
if (!hasSlug(slug)) {
redirect(res, DEFAULT);
log.unknown(req, slug);
return;
}
let url = getUrl(slug, true);
redirect(res, url, REDIRECT_STATUS);
log.get(req, slug);
}
/**
* Catch-all handler.
*/
function catchallHandler([url], req, res) {
redirect(res, DEFAULT);
log.catchall(req);
}
/**
* Redirection helper.
*/
function redirect(res, target, status = 302) {
if(!DRY_RUN)
res.writeHead(status, { Location: target });
res.end(target);
}