Implement setting api token after response

This commit is contained in:
mrjvs 2023-12-20 15:08:04 +01:00
parent d998dceb1e
commit 4db6dcca48
2 changed files with 11 additions and 2 deletions

View File

@ -1,6 +1,6 @@
import { ofetch } from "ofetch"; import { ofetch } from "ofetch";
import { getApiToken } from "@/backend/helpers/providerApi"; import { getApiToken, setApiToken } from "@/backend/helpers/providerApi";
import { getLoadbalancedProxyUrl } from "@/utils/providers"; import { getLoadbalancedProxyUrl } from "@/utils/providers";
type P<T> = Parameters<typeof ofetch<T, any>>; type P<T> = Parameters<typeof ofetch<T, any>>;
@ -66,6 +66,11 @@ export async function singularProxiedFetch<T>(
}, },
query: {}, query: {},
headers, headers,
onResponse(context) {
const tokenHeader = context.response.headers.get("X-Token");
if (tokenHeader) setApiToken(tokenHeader);
ops.onResponse?.(context);
},
}); });
} }

View File

@ -15,6 +15,10 @@ export function getCachedMetadata(): MetaOutput[] {
return metaDataCache ?? []; return metaDataCache ?? [];
} }
export function setApiToken(newToken: string) {
token = newToken;
}
function getTokenIfValid(): null | string { function getTokenIfValid(): null | string {
if (!token) return null; if (!token) return null;
try { try {
@ -116,7 +120,7 @@ export async function connectServerSideEvents<T>(
}); });
eventSource.addEventListener("token", (e) => { eventSource.addEventListener("token", (e) => {
token = JSON.parse(e.data); setApiToken(JSON.parse(e.data));
}); });
eventSource.addEventListener("error", (err: MessageEvent<any>) => { eventSource.addEventListener("error", (err: MessageEvent<any>) => {