From 4db6dcca48b50843d4ee459208430c7465609ef9 Mon Sep 17 00:00:00 2001 From: mrjvs Date: Wed, 20 Dec 2023 15:08:04 +0100 Subject: [PATCH] Implement setting api token after response --- src/backend/helpers/fetch.ts | 7 ++++++- src/backend/helpers/providerApi.ts | 6 +++++- 2 files changed, 11 insertions(+), 2 deletions(-) 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) => {