forked from barretlee/cloudflare-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcloudflare-worker.js
48 lines (44 loc) · 1.21 KB
/
cloudflare-worker.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
addEventListener("fetch", (event) => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
const url = new URL(request.url);
const fetchAPI = request.url.replace(url.host, 'api.openai.com');
let body;
if (request.method === 'POST') {
body = await request.json();
}
const authKey = request.headers.get('Authorization');
if (!authKey) {
return new Response("Not allowed", {
status: 403
});
}
const payload = {
method: request.method,
headers: {
"Content-Type": "application/json",
Authorization: authKey,
},
body: typeof body === 'object' ? JSON.stringify(body) : '{}',
};
if (['HEAD', 'GET'].includes(request.method)) {
delete payload.body;
}
if (body && body.stream && body.stream === false) {
const results = await response.json();
return new Response(JSON.stringify(results), {
status: response.status,
headers: {
"Content-Type": "application/json",
},
});
} else {
const response = await fetch(fetchAPI, payload);
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: response.headers,
});
}
}