refactor: merge token and access code

This commit is contained in:
Yidadaa
2023-05-03 23:08:37 +08:00
parent ef5b7ce853
commit 48ebd74859
8 changed files with 119 additions and 101 deletions

View File

@@ -44,14 +44,21 @@ const makeRequestParam = (
function getHeaders() {
const accessStore = useAccessStore.getState();
let headers: Record<string, string> = {};
const headers = {
Authorization: "",
};
if (accessStore.enabledAccessControl()) {
headers["access-code"] = accessStore.accessCode;
}
const makeBearer = (token: string) => `Bearer ${token.trim()}`;
const validString = (x: string) => x && x.length > 0;
if (accessStore.token && accessStore.token.length > 0) {
headers["token"] = accessStore.token;
// use user's api key first
if (validString(accessStore.token)) {
headers.Authorization = makeBearer(accessStore.token);
} else if (
accessStore.enabledAccessControl() &&
validString(accessStore.accessCode)
) {
headers.Authorization = makeBearer(accessStore.accessCode);
}
return headers;
@@ -59,13 +66,8 @@ function getHeaders() {
export function requestOpenaiClient(path: string) {
return (body: any, method = "POST") =>
fetch("/api/openai", {
fetch("/api/openai/" + path, {
method,
headers: {
"Content-Type": "application/json",
path,
...getHeaders(),
},
body: body && JSON.stringify(body),
});
}
@@ -161,16 +163,16 @@ export async function requestChatStream(
const reqTimeoutId = setTimeout(() => controller.abort(), TIME_OUT_MS);
try {
const res = await fetch("/api/openai", {
const res = await fetch("/api/openai/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
path: "v1/chat/completions",
...getHeaders(),
},
body: JSON.stringify(req),
signal: controller.signal,
});
clearTimeout(reqTimeoutId);
let responseText = "";