fix: little fixes
This commit is contained in:
@@ -3,7 +3,56 @@ import createClient from "openapi-fetch";
|
||||
import { apiBaseUrl } from "./config";
|
||||
import type { paths } from "./generated/schema";
|
||||
|
||||
type AuthHandlers = {
|
||||
accessToken: () => string | null;
|
||||
refresh: () => Promise<boolean>;
|
||||
clear: () => void;
|
||||
};
|
||||
|
||||
let auth: AuthHandlers | null = null;
|
||||
|
||||
export function configureAuthClient(handlers: AuthHandlers | null) {
|
||||
auth = handlers;
|
||||
}
|
||||
|
||||
async function authenticatedFetch(request: Request): Promise<Response> {
|
||||
const isAuthRequest = new URL(request.url).pathname.startsWith(
|
||||
"/api/v1/auth/",
|
||||
);
|
||||
const token = auth?.accessToken();
|
||||
const withToken = (source: Request, value: string) => {
|
||||
const headers = new Headers(source.headers);
|
||||
headers.set("Authorization", `Bearer ${value}`);
|
||||
return new Request(source, { headers });
|
||||
};
|
||||
const authorized =
|
||||
token && !isAuthRequest ? withToken(request, token) : request;
|
||||
const retryRequest = authorized.clone();
|
||||
const response = await fetch(authorized);
|
||||
if (
|
||||
response.status !== 401 ||
|
||||
isAuthRequest ||
|
||||
!auth ||
|
||||
(
|
||||
await response
|
||||
.clone()
|
||||
.json()
|
||||
.catch(() => null)
|
||||
)?.code !== "UNAUTHORIZED"
|
||||
)
|
||||
return response;
|
||||
if (!(await auth.refresh())) {
|
||||
auth.clear();
|
||||
return response;
|
||||
}
|
||||
const refreshedToken = auth.accessToken();
|
||||
return refreshedToken
|
||||
? fetch(withToken(retryRequest, refreshedToken))
|
||||
: response;
|
||||
}
|
||||
|
||||
export const apiClient = createClient<paths>({
|
||||
baseUrl: apiBaseUrl,
|
||||
credentials: "include",
|
||||
fetch: authenticatedFetch,
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user