Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
328 lines (302 loc) · 9.39 KB
/
Copy pathserver.js
File metadata and controls
328 lines (302 loc) · 9.39 KB
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
const http = require('http');
const { URL } = require('url');
const { JsonUrlStore } = require('./storage/json-url-store');
const { UrlRepository } = require('./storage/url-repository');
const PORT = Number(process.env.PORT || 3000);
const HOST = process.env.HOST || '127.0.0.1';
const BASE_URL = process.env.BASE_URL || `http://${HOST}:${PORT}`;
const SAMPLE_URLS = [
'https://intent-driven.dev/',
'https://manning.com/'
];
const repository = new UrlRepository(new JsonUrlStore());
function normalizeUrl(input) {
const raw = String(input || '').trim();
if (!raw) return null;
try {
return new URL(raw).toString();
} catch {
try {
return new URL(`https://${raw}`).toString();
} catch {
return null;
}
}
}
function escapeHtml(value) {
return String(value)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function pageTemplate(body) {
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>URL Shortener</title>
<style>
:root { color-scheme: light; }
body {
margin: 0;
font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
background: #f4f7fb;
color: #102033;
}
main {
max-width: 760px;
margin: 0 auto;
padding: 48px 20px;
}
h1 { margin: 0 0 12px; font-size: 2rem; }
p { line-height: 1.5; }
form, .panel {
background: #fff;
border: 1px solid #d9e2ef;
border-radius: 12px;
padding: 20px;
box-shadow: 0 6px 20px rgba(16, 32, 51, 0.06);
}
.field { display: grid; gap: 10px; margin-top: 12px; }
label { font-weight: 600; }
input[type="url"], input[type="text"] {
width: 100%;
box-sizing: border-box;
padding: 14px 16px;
border: 1px solid #b8c4d6;
border-radius: 10px;
font-size: 1rem;
}
button, .button {
display: inline-block;
margin-top: 14px;
padding: 12px 16px;
border: 0;
border-radius: 10px;
background: #155eef;
color: #fff;
font-size: 1rem;
text-decoration: none;
cursor: pointer;
}
.error {
margin: 16px 0 0;
color: #b42318;
background: #fff5f5;
border: 1px solid #f5c2c7;
border-radius: 10px;
padding: 12px 14px;
}
.success { margin-top: 18px; }
.stack { display: grid; gap: 12px; }
code {
display: block;
padding: 12px 14px;
background: #f3f6fb;
border: 1px solid #d9e2ef;
border-radius: 10px;
overflow-wrap: anywhere;
}
.muted { color: #55657d; }
</style>
</head>
<body>
<main>
${body}
</main>
</body>
</html>`;
}
function homePage(errorMessage) {
return pageTemplate(`
<h1>URL Shortener</h1>
<p class="muted">Paste a long URL and get a short link that redirects to it for 90 days.</p>
<p><a class="button" href="/urls">View created URLs</a></p>
<form method="post" action="/shorten">
<div class="field">
<label for="longUrl">Long URL</label>
<input id="longUrl" name="longUrl" type="url" placeholder="https://example.com/some/very/long/path" required>
</div>
<button type="submit">Create short URL</button>
${errorMessage ? `<div class="error">${escapeHtml(errorMessage)}</div>` : ''}
</form>
`);
}
function resultPage(shortUrl, longUrl) {
return pageTemplate(`
<h1>Short URL created</h1>
<p class="muted">This link redirects to the original URL and expires 90 days after creation.</p>
<div class="panel stack">
<div>
<label class="muted">Short URL</label>
<code id="shortUrl">${escapeHtml(shortUrl)}</code>
</div>
<div>
<label class="muted">Original URL</label>
<code>${escapeHtml(longUrl)}</code>
</div>
<div>
<a class="button" href="/">Create another</a>
<a class="button" href="/urls" style="margin-left: 8px;">View created URLs</a>
</div>
</div>
`);
}
function urlsPage(entries) {
const rows = entries
.map((entry, index) => `
<tr>
<td>${index + 1}</td>
<td><code>${escapeHtml(`${BASE_URL}/${entry.code}`)}</code></td>
<td><code>${escapeHtml(entry.longUrl)}</code></td>
<td>${escapeHtml(new Date(entry.expiresAt).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' }))}</td>
</tr>
`)
.join('');
return pageTemplate(`
<h1>Created URLs</h1>
<p class="muted">Only active links are shown here. Each link expires 90 days after creation.</p>
<div class="panel">
<div class="stack">
<div><a class="button" href="/">Create a new short URL</a></div>
<div><strong>Total:</strong> ${entries.length}</div>
</div>
<div style="overflow-x:auto; margin-top:16px;">
<table style="width:100%; border-collapse: collapse;">
<thead>
<tr>
<th style="text-align:left; padding:10px 8px; border-bottom:1px solid #d9e2ef;">#</th>
<th style="text-align:left; padding:10px 8px; border-bottom:1px solid #d9e2ef;">Short URL</th>
<th style="text-align:left; padding:10px 8px; border-bottom:1px solid #d9e2ef;">Original URL</th>
<th style="text-align:left; padding:10px 8px; border-bottom:1px solid #d9e2ef;">Expires</th>
</tr>
</thead>
<tbody>
${rows || `
<tr>
<td colspan="4" style="padding:14px 8px; color:#55657d;">No URLs have been created yet.</td>
</tr>
`}
</tbody>
</table>
</div>
</div>
`);
}
function notFoundPage() {
return pageTemplate(`
<h1>Not found</h1>
<p class="muted">That short code does not exist.</p>
<a class="button" href="/">Go home</a>
`);
}
function gonePage() {
return pageTemplate(`
<h1>Link expired</h1>
<p class="muted">This short URL expired after 90 days and no longer redirects.</p>
<a class="button" href="/">Go home</a>
`);
}
function readBody(req) {
return new Promise((resolve, reject) => {
let data = '';
req.on('data', chunk => {
data += chunk;
if (data.length > 1e6) {
reject(new Error('Request body too large'));
req.destroy();
}
});
req.on('end', () => resolve(data));
req.on('error', reject);
});
}
function parseForm(body) {
const params = new URLSearchParams(body);
return Object.fromEntries(params.entries());
}
function getRequestOrigin(req) {
const forwardedProto = String(req.headers['x-forwarded-proto'] || '').split(',')[0].trim();
const protocol = forwardedProto || 'http';
const host = req.headers.host || `localhost:${PORT}`;
return `${protocol}://${host}`;
}
async function seedSampleUrls() {
for (const sampleUrl of SAMPLE_URLS) {
const normalized = normalizeUrl(sampleUrl);
if (normalized) {
await repository.createOrGet(normalized);
}
}
}
async function start() {
await repository.init();
await seedSampleUrls();
const server = http.createServer(async (req, res) => {
try {
const requestUrl = new URL(req.url, BASE_URL);
if (req.method === 'GET' && requestUrl.pathname === '/') {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(homePage(''));
return;
}
if (req.method === 'POST' && requestUrl.pathname === '/shorten') {
const body = await readBody(req);
const { longUrl } = parseForm(body);
const normalized = normalizeUrl(longUrl);
if (!normalized) {
res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(homePage('Please enter a valid URL.'));
return;
}
const record = await repository.createOrGet(normalized);
const shortUrl = `${getRequestOrigin(req)}/${record.code}`;
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(resultPage(shortUrl, normalized));
return;
}
if (req.method === 'GET' && requestUrl.pathname === '/urls') {
const entries = await repository.list();
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(urlsPage(entries));
return;
}
if (req.method === 'GET') {
const code = requestUrl.pathname.replace(/^\/+/, '');
if (code) {
const record = await repository.findByCode(code);
if (record) {
if (Number.isFinite(record.expiresAt) && record.expiresAt <= Date.now()) {
res.writeHead(410, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(gonePage());
return;
}
res.writeHead(302, { Location: record.longUrl });
res.end();
return;
}
}
}
res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(notFoundPage());
} catch (error) {
console.error(error);
if (!res.headersSent) {
res.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end(`Internal Server Error: ${error.message}`);
return;
}
res.destroy(error);
}
});
server.listen(PORT, HOST, () => {
console.log(`URL shortener running at ${BASE_URL}`);
});
}
start().catch(error => {
console.error(error);
process.exit(1);
});