-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworkers.js
71 lines (58 loc) · 2.08 KB
/
workers.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
// Accessing a secret named "API_KEY"
const apiKey = SECRETS.API_KEY;
// Cloudflare Worker for Firestore CRUD
addEventListener('fetch', (event) => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
const url = new URL(request.url);
const path = url.pathname.split('/').filter(Boolean);
const projectId = 'your-firebase-project-id';
const firestoreUrl = `https://firestore.googleapis.com/v1/projects/${projectId}/databases/(default)/documents/${path.join('/')}`;
// Forward the request to Firestore
const firestoreResponse = await fetch(firestoreUrl, {
method: request.method,
headers: {
...request.headers,
'Content-Type': 'application/json',
},
body: request.method !== 'GET' ? await request.json() : undefined,
});
// Modify or filter response as needed
const responseBody = await firestoreResponse.json();
// Return the modified or filtered response
return new Response(JSON.stringify(responseBody), {
status: firestoreResponse.status,
headers: {
'Content-Type': 'application/json',
},
});
}
// Cloudflare Worker for Realtime Database CRUD
addEventListener('fetch', (event) => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
const url = new URL(request.url);
const path = url.pathname.split('/').filter(Boolean);
const projectId = 'your-firebase-project-id';
const databaseUrl = `https://${projectId}.firebaseio.com/${path.join('/')}.json`;
// Forward the request to Realtime Database
const databaseResponse = await fetch(databaseUrl, {
method: request.method,
headers: {
...request.headers,
'Content-Type': 'application/json',
},
body: request.method !== 'GET' ? await request.json() : undefined,
});
// Modify or filter response as needed
const responseBody = await databaseResponse.json();
// Return the modified or filtered response
return new Response(JSON.stringify(responseBody), {
status: databaseResponse.status,
headers: {
'Content-Type': 'application/json',
},
});
}