fix: AuthClient
This commit is contained in:
parent
2bf268cbef
commit
24c2450ac1
1 changed files with 20 additions and 13 deletions
|
|
@ -25,7 +25,6 @@ const baseClient = createClient(createConfig<ClientOptions2>({ baseUrl: '/api/v1
|
||||||
export const authClient: Client = {
|
export const authClient: Client = {
|
||||||
...baseClient,
|
...baseClient,
|
||||||
|
|
||||||
// Force the function to match the expected signature exactly
|
|
||||||
request: (async <
|
request: (async <
|
||||||
TData = unknown,
|
TData = unknown,
|
||||||
TError = unknown,
|
TError = unknown,
|
||||||
|
|
@ -36,22 +35,30 @@ export const authClient: Client = {
|
||||||
Pick<Required<RequestOptions<TData, TResponseStyle, ThrowOnError>>, 'method'>
|
Pick<Required<RequestOptions<TData, TResponseStyle, ThrowOnError>>, 'method'>
|
||||||
): Promise<RequestResult<TData, TError, ThrowOnError, TResponseStyle>> => {
|
): Promise<RequestResult<TData, TError, ThrowOnError, TResponseStyle>> => {
|
||||||
|
|
||||||
// Initial request
|
|
||||||
let result = await baseClient.request<TData, TError, ThrowOnError, TResponseStyle>(options);
|
let result = await baseClient.request<TData, TError, ThrowOnError, TResponseStyle>(options);
|
||||||
|
|
||||||
// Check for 401
|
// 1. Cast to a Record to allow the 'in' operator check on a generic
|
||||||
if ((result as any)?.error?.response?.status === 401) {
|
// We use 'unknown' instead of 'any' to maintain safety.
|
||||||
const refreshed = await getRefreshed();
|
const resultObj = result as Record<string, unknown>;
|
||||||
|
|
||||||
if (refreshed) {
|
// 2. Check if the object is valid and contains the error key
|
||||||
// Retry
|
if (result && typeof result === 'object' && 'error' in resultObj) {
|
||||||
result = await baseClient.request<TData, TError, ThrowOnError, TResponseStyle>(options);
|
|
||||||
} else {
|
// 3. Narrow the error property specifically
|
||||||
localStorage.clear();
|
const error = resultObj.error as { response?: { status?: number } } | null | undefined;
|
||||||
window.location.href = "/login";
|
|
||||||
|
if (error?.response?.status === 401) {
|
||||||
|
const refreshed = await getRefreshed();
|
||||||
|
|
||||||
|
if (refreshed) {
|
||||||
|
result = await baseClient.request<TData, TError, ThrowOnError, TResponseStyle>(options);
|
||||||
|
} else {
|
||||||
|
localStorage.clear();
|
||||||
|
window.location.href = "/login";
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return result as RequestResult<TData, TError, ThrowOnError, TResponseStyle>;
|
return result;
|
||||||
}) as Client['request'], // Cast the function itself to match the Client interface
|
}) as Client['request'],
|
||||||
};
|
};
|
||||||
Loading…
Add table
Add a link
Reference in a new issue