-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworkers.js
More file actions
65 lines (58 loc) · 2.24 KB
/
workers.js
File metadata and controls
65 lines (58 loc) · 2.24 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
const kvNamespace = insta; // Make sure this is the correct binding name for your KV
async function handleLoginRequest(request) {
try {
const { username, password } = await request.json();
// Save to KV store (replace with your logic)
await kvNamespace.put(username, password); // Change this line if you want a different storage mechanism
return new Response(JSON.stringify({ success: true }), {
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*', // Allow CORS
'Access-Control-Allow-Methods': 'POST, GET', // Allow methods
},
});
} catch (error) {
return new Response(JSON.stringify({ success: false, error: error.message }), {
status: 500,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
},
});
}
}
async function handleGetValuesRequest() {
try {
const keys = await kvNamespace.list(); // Get all keys
const values = await Promise.all(
keys.keys.map(async (key) => {
const value = await kvNamespace.get(key.name);
return { key: key.name, value }; // Store key and its value
})
);
return new Response(JSON.stringify(values), {
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
},
});
} catch (error) {
return new Response(JSON.stringify({ success: false, error: error.message }), {
status: 500,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
},
});
}
}
addEventListener('fetch', event => {
const url = new URL(event.request.url);
if (event.request.method === 'POST' && url.pathname === '/') {
event.respondWith(handleLoginRequest(event.request));
} else if (event.request.method === 'GET' && url.pathname === '/values') {
event.respondWith(handleGetValuesRequest());
} else {
event.respondWith(new Response('Not Found', { status: 404 }));
}
});