Compare commits
2 commits
27acfab0cd
...
2bf268cbef
| Author | SHA1 | Date | |
|---|---|---|---|
| 2bf268cbef | |||
| ca68f8bdf5 |
1 changed files with 25 additions and 23 deletions
|
|
@ -10,15 +10,13 @@ async function getRefreshed(): Promise<boolean> {
|
|||
if (!refreshPromise) {
|
||||
refreshPromise = (async () => {
|
||||
try {
|
||||
const res = await refreshTokens();
|
||||
// consider refresh successful if res.data exists
|
||||
const res = await refreshTokens({ throwOnError: true });
|
||||
return !!res.data;
|
||||
} catch (err) {
|
||||
return false; // failed to refresh
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
return refreshPromise;
|
||||
}
|
||||
|
||||
|
|
@ -27,29 +25,33 @@ const baseClient = createClient(createConfig<ClientOptions2>({ baseUrl: '/api/v1
|
|||
export const authClient: Client = {
|
||||
...baseClient,
|
||||
|
||||
request: function <
|
||||
// Force the function to match the expected signature exactly
|
||||
request: (async <
|
||||
TData = unknown,
|
||||
TError = unknown,
|
||||
ThrowOnError extends boolean = true,
|
||||
ThrowOnError extends boolean = false,
|
||||
TResponseStyle extends ResponseStyle = 'fields',
|
||||
>(
|
||||
options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, 'method'> &
|
||||
Pick<Required<RequestOptions<TData, TResponseStyle, ThrowOnError>>, 'method'>
|
||||
): RequestResult<TData, TError, ThrowOnError, TResponseStyle> {
|
||||
): Promise<RequestResult<TData, TError, ThrowOnError, TResponseStyle>> => {
|
||||
|
||||
// Wrap logic inside a Promise to satisfy RequestResult type
|
||||
return baseClient.request<TData, TError, ThrowOnError, TResponseStyle>(options).catch(async (err: any) => {
|
||||
if (err?.status === 401) {
|
||||
// Initial request
|
||||
let result = await baseClient.request<TData, TError, ThrowOnError, TResponseStyle>(options);
|
||||
|
||||
// Check for 401
|
||||
if ((result as any)?.error?.response?.status === 401) {
|
||||
const refreshed = await getRefreshed();
|
||||
if (!refreshed) {
|
||||
|
||||
if (refreshed) {
|
||||
// Retry
|
||||
result = await baseClient.request<TData, TError, ThrowOnError, TResponseStyle>(options);
|
||||
} else {
|
||||
localStorage.clear();
|
||||
window.location.href = "/login";
|
||||
throw err;
|
||||
}
|
||||
// Retry original request
|
||||
return baseClient.request<TData, TError, ThrowOnError, TResponseStyle>(options);
|
||||
}
|
||||
throw err;
|
||||
}) as RequestResult<TData, TError, ThrowOnError, TResponseStyle>;
|
||||
},
|
||||
|
||||
return result as RequestResult<TData, TError, ThrowOnError, TResponseStyle>;
|
||||
}) as Client['request'], // Cast the function itself to match the Client interface
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue