diff --git a/packages/frontend/src/api.ts b/packages/frontend/src/api.ts index 5787f6b..1449857 100644 --- a/packages/frontend/src/api.ts +++ b/packages/frontend/src/api.ts @@ -3,18 +3,24 @@ import { type GetEndpoints, type PostEndpoints, createApiClient } from "./api.ge import { ENV } from "./envVars"; import { createStore, get, set } from "idb-keyval"; +import { getTokenOrRefresh } from "./db/Connector"; export const apiStore = createStore("auth", "access"); export const createApiClientWithUrl = (url: string) => { - return createApiClient((method, url, parameters) => { + return createApiClient(async (method, url, parameters) => { const { body, query, header } = parameters || {}; + let token; + if (ref.token) { + token = await getTokenOrRefresh(); + } + return ofetch(url, { method, body: body as any, query, - headers: { ...header, Authorization: ref.token ? `Bearer ${ref.token}` : undefined } as Record, + headers: { ...header, Authorization: token ? `Bearer ${token}` : undefined } as Record, }); }, url); }; @@ -27,6 +33,7 @@ const ref = { export const setToken = (token?: string | null) => { ref.token = token ?? null; + set("token", token, apiStore); }; diff --git a/packages/frontend/src/db/Connector.ts b/packages/frontend/src/db/Connector.ts index c513c63..69dabc7 100644 --- a/packages/frontend/src/db/Connector.ts +++ b/packages/frontend/src/db/Connector.ts @@ -53,7 +53,7 @@ export class Connector implements PowerSyncBackendConnector { } } -const getTokenOrRefresh = async () => { +export const getTokenOrRefresh = async () => { const authData = safeJSONParse(window.localStorage.getItem("crvif/auth") ?? ""); if (!authData) throw new Error("No auth data found"); @@ -71,5 +71,5 @@ const getTokenOrRefresh = async () => { } } - return authData.token; + return authData.token as string; };