0
Fork 0
mirror of https://github.com/logto-io/logto.git synced 2024-12-16 20:26:19 -05:00

refactor(console): refactor useApi (#5549)

refactor useApi hideToast logic
This commit is contained in:
simeng-li 2024-03-27 11:49:33 +08:00 committed by GitHub
parent 92d45f2432
commit affcecd0c6
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -4,6 +4,7 @@ import {
httpCodeToMessage, httpCodeToMessage,
organizationUrnPrefix, organizationUrnPrefix,
} from '@logto/core-kit'; } from '@logto/core-kit';
import { type LogtoErrorCode } from '@logto/phrases';
import { useLogto } from '@logto/react'; import { useLogto } from '@logto/react';
import { import {
getTenantOrganizationId, getTenantOrganizationId,
@ -37,21 +38,18 @@ export class RequestError extends Error {
export type StaticApiProps = { export type StaticApiProps = {
prefixUrl?: URL; prefixUrl?: URL;
hideErrorToast?: boolean; hideErrorToast?: boolean | LogtoErrorCode[];
resourceIndicator: string; resourceIndicator: string;
}; };
export const useStaticApi = ({ const useGlobalRequestErrorHandler = (toastDisabledErrorCodes?: LogtoErrorCode[]) => {
prefixUrl, const { signOut } = useLogto();
hideErrorToast,
resourceIndicator,
}: StaticApiProps): KyInstance => {
const { isAuthenticated, getAccessToken, getOrganizationToken, signOut } = useLogto();
const { t, i18n } = useTranslation(undefined, { keyPrefix: 'admin_console' });
const { show } = useConfirmModal(); const { show } = useConfirmModal();
const { t } = useTranslation(undefined, { keyPrefix: 'admin_console' });
const postSignOutRedirectUri = useRedirectUri('signOut'); const postSignOutRedirectUri = useRedirectUri('signOut');
const toastError = useCallback( const handleError = useCallback(
async (response: Response) => { async (response: Response) => {
const fallbackErrorMessage = t('errors.unknown_server_error'); const fallbackErrorMessage = t('errors.unknown_server_error');
@ -81,14 +79,48 @@ export const useStaticApi = ({
return; return;
} }
// Skip showing toast for specific error codes.
if (toastDisabledErrorCodes?.includes(data.code)) {
return;
}
toast.error([data.message, data.details].join('\n') || fallbackErrorMessage); toast.error([data.message, data.details].join('\n') || fallbackErrorMessage);
} catch { } catch {
toast.error(httpCodeToMessage[response.status] ?? fallbackErrorMessage); toast.error(httpCodeToMessage[response.status] ?? fallbackErrorMessage);
} }
}, },
[show, signOut, t, postSignOutRedirectUri] [t, toastDisabledErrorCodes, signOut, postSignOutRedirectUri.href, show]
); );
return {
handleError,
};
};
/**
*
* @param {StaticApiProps} props
* @param {URL} props.prefixUrl The base URL for the API.
* @param {boolean} props.hideErrorToast Whether to disable the global error handling.
* @param {string} props.resourceIndicator The resource indicator for the API. Used by the Logto SDK to validate the access token.
*
* @returns
*/
export const useStaticApi = ({
prefixUrl,
hideErrorToast,
resourceIndicator,
}: StaticApiProps): KyInstance => {
const { isAuthenticated, getAccessToken, getOrganizationToken } = useLogto();
const { i18n } = useTranslation(undefined, { keyPrefix: 'admin_console' });
// Disable global error handling if `hideErrorToast` is true.
const disableGlobalErrorHandling = hideErrorToast === true;
// Disable toast for specific error codes.
const toastDisabledErrorCodes = Array.isArray(hideErrorToast) ? hideErrorToast : undefined;
const { handleError } = useGlobalRequestErrorHandler(toastDisabledErrorCodes);
const api = useMemo( const api = useMemo(
() => () =>
ky.create({ ky.create({
@ -96,9 +128,9 @@ export const useStaticApi = ({
timeout: requestTimeout, timeout: requestTimeout,
hooks: { hooks: {
beforeError: conditionalArray( beforeError: conditionalArray(
!hideErrorToast && !disableGlobalErrorHandling &&
(async (error) => { (async (error) => {
await toastError(error.response); await handleError(error.response);
return error; return error;
}) })
), ),
@ -117,8 +149,8 @@ export const useStaticApi = ({
}), }),
[ [
prefixUrl, prefixUrl,
hideErrorToast, disableGlobalErrorHandling,
toastError, handleError,
isAuthenticated, isAuthenticated,
resourceIndicator, resourceIndicator,
getOrganizationToken, getOrganizationToken,