Skip to content

Commit

Permalink
fix: refresh token when needed
Browse files Browse the repository at this point in the history
  • Loading branch information
ledouxm committed Dec 11, 2024
1 parent 68037b0 commit aa3bb25
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
11 changes: 9 additions & 2 deletions packages/frontend/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string>,
headers: { ...header, Authorization: token ? `Bearer ${token}` : undefined } as Record<string, string>,
});
}, url);
};
Expand All @@ -27,6 +33,7 @@ const ref = {

export const setToken = (token?: string | null) => {
ref.token = token ?? null;

set("token", token, apiStore);
};

Expand Down
4 changes: 2 additions & 2 deletions packages/frontend/src/db/Connector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");

Expand All @@ -71,5 +71,5 @@ const getTokenOrRefresh = async () => {
}
}

return authData.token;
return authData.token as string;
};

0 comments on commit aa3bb25

Please sign in to comment.