-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
72 lines (59 loc) · 1.98 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
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
})
const KV_NAMESPACE = 'LINKS';
async function handleRequest(request) {
const { pathname, searchParams } = new URL(request.url);
if (pathname.startsWith('/add')) {
return handleAddUrl(request, searchParams); // Pass request as an argument
} else if (pathname.startsWith('/short/')) {
return handleShortUrl(pathname.split('/short/')[1]);
} else {
return new Response(JSON.stringify({ error: true, message: 'Invalid endpoint' }), {
headers: { 'Content-Type': 'application/json' },
status: 400
});
}
}
async function handleAddUrl(request, params) { // Receive request as an argument
const longUrl = params.get('url');
if (!longUrl) {
return new Response(JSON.stringify({ error: true, message: 'URL parameter is missing' }), {
headers: { 'Content-Type': 'application/json' },
status: 400
});
}
const key = generateKey();
await LINKS.put(key, longUrl);
const shortUrl = `${new URL(request.url).origin}/short/${key}`;
return new Response(JSON.stringify({ error: false, short_url: shortUrl }), {
headers: { 'Content-Type': 'application/json' }
});
}
async function handleShortUrl(key) {
if (!key) {
return new Response(JSON.stringify({ error: true, message: 'Key is missing' }), {
headers: { 'Content-Type': 'application/json' },
status: 400
});
}
const longUrl = await LINKS.get(key);
if (!longUrl) {
return new Response(JSON.stringify({ error: true, message: 'URL not found' }), {
headers: { 'Content-Type': 'application/json' },
status: 404
});
}
const apiResponse = await fetch(longUrl, {
});
return apiResponse;
}
function generateKey() {
const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let key = '';
for (let i = 0; i < 10; i++) {
const randomIndex = Math.floor(Math.random() * charset.length);
key += charset[randomIndex];
}
return key;
}