diff --git a/src/backend/helpers/fetch.ts b/src/backend/helpers/fetch.ts index 646d8ab9..96762f74 100644 --- a/src/backend/helpers/fetch.ts +++ b/src/backend/helpers/fetch.ts @@ -1,6 +1,6 @@ import { ofetch } from "ofetch"; -import { getApiToken } from "@/backend/helpers/providerApi"; +import { getApiToken, setApiToken } from "@/backend/helpers/providerApi"; import { getLoadbalancedProxyUrl } from "@/utils/providers"; type P = Parameters>; @@ -66,6 +66,11 @@ export async function singularProxiedFetch( }, query: {}, headers, + onResponse(context) { + const tokenHeader = context.response.headers.get("X-Token"); + if (tokenHeader) setApiToken(tokenHeader); + ops.onResponse?.(context); + }, }); } diff --git a/src/backend/helpers/providerApi.ts b/src/backend/helpers/providerApi.ts index 89d3eb13..632a1eb8 100644 --- a/src/backend/helpers/providerApi.ts +++ b/src/backend/helpers/providerApi.ts @@ -15,6 +15,10 @@ export function getCachedMetadata(): MetaOutput[] { return metaDataCache ?? []; } +export function setApiToken(newToken: string) { + token = newToken; +} + function getTokenIfValid(): null | string { if (!token) return null; try { @@ -116,7 +120,7 @@ export async function connectServerSideEvents( }); eventSource.addEventListener("token", (e) => { - token = JSON.parse(e.data); + setApiToken(JSON.parse(e.data)); }); eventSource.addEventListener("error", (err: MessageEvent) => {