mirror of
https://gitea.com/PublicAffairs/openai-github-copilot.git
synced 2025-07-23 20:30:45 +02:00
Refactor (minor)
This commit is contained in:
@@ -32,19 +32,18 @@ export default {
|
||||
console.error(e);
|
||||
}
|
||||
if (!token) {
|
||||
let errResponse;
|
||||
({ token, errResponse } = await getToken(authKey));
|
||||
let expires_at, errResponse;
|
||||
({ token, expires_at, errResponse } = await getToken(authKey));
|
||||
if (errResponse) { return errResponse; }
|
||||
const expiration = token.match(/;exp=(\d+);/)?.[1];
|
||||
if (expiration) {
|
||||
if (expires_at) {
|
||||
try {
|
||||
await tokenCache.put(authKey, token, { expiration });
|
||||
await tokenCache.put(authKey, token, { expiration: expires_at });
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
return makeRequest(request, url.pathname, await makeHeaders(token));
|
||||
return makeRequest(request, url.pathname, token);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -86,18 +85,18 @@ const getToken = async (authKey) => {
|
||||
return { errResponse: response };
|
||||
}
|
||||
const text = await response.text();
|
||||
let token;
|
||||
let data;
|
||||
try {
|
||||
token = JSON.parse(text)["token"];
|
||||
data = JSON.parse(text);
|
||||
} catch (e) {
|
||||
console.error(e.message,"\n",text);
|
||||
return { errResponse: new Response(e.message + "\n" + text, { status: 400 }) };
|
||||
}
|
||||
if (!token) {
|
||||
console.error("token not found:\n", text);
|
||||
if (!data.token) {
|
||||
console.error("token not found:\n", data);
|
||||
return { errResponse: new Response("token not found:\n" + text, { status: 400 }) };
|
||||
}
|
||||
return { token };
|
||||
return data;
|
||||
};
|
||||
|
||||
const makeHeaders = async (token) => {
|
||||
@@ -126,16 +125,16 @@ const makeHeaders = async (token) => {
|
||||
};
|
||||
};
|
||||
|
||||
const makeRequest = async (request, path, headers) => {
|
||||
const makeRequest = async (request, path, token) => {
|
||||
if (path.startsWith("/v1/")) {
|
||||
path = path.substring(3);
|
||||
}
|
||||
const response = await fetch(`https://api.githubcopilot.com${path}`, {
|
||||
method: request.method,
|
||||
headers,
|
||||
headers: await makeHeaders(token),
|
||||
body: request.body,
|
||||
});
|
||||
headers = new Headers(response.headers);
|
||||
const headers = new Headers(response.headers);
|
||||
headers.set("Access-Control-Allow-Origin", "*");
|
||||
let body;
|
||||
if (response.ok && path === "/chat/completions" && request.method === "POST") {
|
||||
|
Reference in New Issue
Block a user