-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
191 lines (157 loc) · 4.53 KB
/
Copy pathserver.js
File metadata and controls
191 lines (157 loc) · 4.53 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
'use strict';
const http = require('http');
const path = require('path');
const { reserveUniqueShortCode } = require('./lib/code-generator');
const { UrlStore } = require('./lib/url-store');
const { scheduleDailyUtcCleanup } = require('./lib/url-cleanup');
const { isValidHttpUrl } = require('./lib/url-validation');
function defaultDataFilePath() {
return path.join(__dirname, 'data', 'urls.json');
}
function sendJson(res, statusCode, payload) {
res.writeHead(statusCode, {
'content-type': 'application/json; charset=utf-8',
});
res.end(`${JSON.stringify(payload)}\n`);
}
function sendText(res, statusCode, body) {
res.writeHead(statusCode, {
'content-type': 'text/plain; charset=utf-8',
});
res.end(`${body}\n`);
}
function readRequestBody(req) {
return new Promise((resolve, reject) => {
const chunks = [];
req.on('data', (chunk) => {
chunks.push(chunk);
});
req.on('end', () => {
resolve(Buffer.concat(chunks).toString('utf8'));
});
req.on('error', reject);
});
}
function extractLongUrl(rawBody, contentType) {
const body = rawBody.trim();
if (!body) {
return null;
}
if (contentType.includes('application/json')) {
try {
const parsed = JSON.parse(body);
return parsed.longUrl || parsed.url || parsed.long_url || null;
} catch {
return null;
}
}
if (contentType.includes('application/x-www-form-urlencoded')) {
const params = new URLSearchParams(body);
return params.get('longUrl') || params.get('url') || params.get('long_url');
}
try {
const parsed = JSON.parse(body);
if (parsed && typeof parsed === 'object') {
return parsed.longUrl || parsed.url || parsed.long_url || null;
}
} catch {
// Fall through to treat the body as a raw URL.
}
if (body.includes('=')) {
const params = new URLSearchParams(body);
const candidate = params.get('longUrl') || params.get('url') || params.get('long_url');
if (candidate) {
return candidate;
}
}
return body;
}
function buildShortUrl(req, code) {
const host = req.headers.host || 'localhost:3000';
return `http://${host}/${code}`;
}
function createRequestHandler(store) {
return async (req, res) => {
try {
const url = new URL(req.url, 'http://localhost');
if (req.method === 'POST' && url.pathname === '/shorten') {
const contentType = String(req.headers['content-type'] || '').toLowerCase();
const rawBody = await readRequestBody(req);
const longUrl = extractLongUrl(rawBody, contentType);
if (!isValidHttpUrl(longUrl)) {
sendJson(res, 400, { error: 'A valid http or https URL is required.' });
return;
}
const code = await reserveUniqueShortCode(store, longUrl);
sendJson(res, 201, {
code,
longUrl,
shortUrl: buildShortUrl(req, code),
});
return;
}
if (req.method === 'GET' && url.pathname.length > 1) {
const code = decodeURIComponent(url.pathname.slice(1));
const longUrl = store.get(code);
if (!longUrl) {
sendText(res, 404, 'Not found');
return;
}
res.writeHead(302, {
location: longUrl,
});
res.end();
return;
}
sendText(res, 404, 'Not found');
} catch (error) {
sendJson(res, 500, {
error: 'Internal server error',
});
}
};
}
async function createServer(options = {}) {
const app = await createApplication(options);
return app.server;
}
async function createApplication(options = {}) {
const store = new UrlStore(options.dataFilePath || defaultDataFilePath());
await store.load();
await store.deleteExpiredRecords();
return {
store,
server: http.createServer(createRequestHandler(store)),
};
}
async function start() {
const port = Number(process.env.PORT || '3000');
const app = await createApplication();
const cleanupJob = scheduleDailyUtcCleanup(app.store, {
onError(error) {
process.stderr.write(
`${error.stack || error.message || 'Expiration cleanup failed'}\n`,
);
},
});
const server = app.server;
server.on('close', () => {
cleanupJob.cancel();
});
server.listen(port, () => {
process.stdout.write(`Listening on port ${port}\n`);
});
return server;
}
if (require.main === module) {
start().catch((error) => {
process.stderr.write(`${error.stack || error.message}\n`);
process.exitCode = 1;
});
}
module.exports = {
createApplication,
createServer,
createRequestHandler,
start,
};