Revert "Client config not render blocking (#12300)" (#12302)

This reverts commit 4ce7fc6987, to take
more time to address PR comments
This commit is contained in:
Félix Malfait
2025-05-27 09:04:47 +02:00
committed by GitHub
parent e8532faaaa
commit 9cdd0fdac0
18 changed files with 148 additions and 776 deletions

View File

@ -1,5 +1,6 @@
import { downloadFile } from '../downloadFile';
// Mock fetch
global.fetch = jest.fn(() =>
Promise.resolve({
status: 200,
@ -15,10 +16,13 @@ window.URL.revokeObjectURL = jest.fn();
// `global.fetch` and `window.fetch` are also undefined
describe.skip('downloadFile', () => {
it('should download a file', () => {
// Call downloadFile
downloadFile('url/to/file.pdf', 'file.pdf');
// Assert on fetch
expect(fetch).toHaveBeenCalledWith('url/to/file.pdf');
// Assert on element creation
const link = document.querySelector(
'a[href="mock-url"][download="file.pdf"]',
);
@ -28,8 +32,10 @@ describe.skip('downloadFile', () => {
// @ts-ignore
expect(link?.style?.display).toBe('none');
// Assert on element click
expect(link).toHaveBeenCalledTimes(1);
// Clean up mocks
jest.clearAllMocks();
});
});

View File

@ -2,11 +2,26 @@ import { useRecoilValue } from 'recoil';
import { clientConfigApiStatusState } from '@/client-config/states/clientConfigApiStatusState';
import { AppFullScreenErrorFallback } from '@/error-handler/components/AppFullScreenErrorFallback';
import { AppPath } from '@/types/AppPath';
import { useLocation } from 'react-router-dom';
import { isMatchingLocation } from '~/utils/isMatchingLocation';
export const ClientConfigProvider: React.FC<React.PropsWithChildren> = ({
children,
}) => {
const { isErrored, error } = useRecoilValue(clientConfigApiStatusState);
const { isLoaded, isErrored, error } = useRecoilValue(
clientConfigApiStatusState,
);
const location = useLocation();
// TODO: Implement a better loading strategy
if (
!isLoaded &&
!isMatchingLocation(location, AppPath.Verify) &&
!isMatchingLocation(location, AppPath.VerifyEmail)
)
return null;
return isErrored && error instanceof Error ? (
<AppFullScreenErrorFallback

View File

@ -1,4 +1,3 @@
import { useClientConfig } from '@/client-config/hooks/useClientConfig';
import { apiConfigState } from '@/client-config/states/apiConfigState';
import { authProvidersState } from '@/client-config/states/authProvidersState';
import { billingState } from '@/client-config/states/billingState';
@ -24,6 +23,7 @@ import { domainConfigurationState } from '@/domain-manager/states/domainConfigur
import { useEffect } from 'react';
import { useRecoilState, useSetRecoilState } from 'recoil';
import { isDefined } from 'twenty-shared/utils';
import { useGetClientConfigQuery } from '~/generated/graphql';
export const ClientConfigProviderEffect = () => {
const setIsDebugMode = useSetRecoilState(isDebugModeState);
@ -87,13 +87,9 @@ export const ClientConfigProviderEffect = () => {
isConfigVariablesInDbEnabledState,
);
const { data, loading, error, fetchClientConfig } = useClientConfig();
useEffect(() => {
if (!clientConfigApiStatus.isLoaded) {
fetchClientConfig();
}
}, [clientConfigApiStatus.isLoaded, fetchClientConfig]);
const { data, loading, error } = useGetClientConfigQuery({
skip: clientConfigApiStatus.isLoaded,
});
useEffect(() => {
if (loading) return;

View File

@ -1,43 +0,0 @@
import { useCallback, useState } from 'react';
import { ClientConfig } from '~/generated/graphql';
import { getClientConfig } from '../utils/clientConfigUtils';
interface UseClientConfigResult {
data: { clientConfig: ClientConfig } | undefined;
loading: boolean;
error: Error | undefined;
fetchClientConfig: () => Promise<void>;
refetchClientConfig: () => Promise<void>;
}
export const useClientConfig = (): UseClientConfigResult => {
const [data, setData] = useState<{ clientConfig: ClientConfig } | undefined>(
undefined,
);
const [loading, setLoading] = useState<boolean>(false);
const [error, setError] = useState<Error | undefined>(undefined);
const fetchClientConfig = useCallback(async () => {
setLoading(true);
setError(undefined);
try {
const clientConfig = await getClientConfig();
setData({ clientConfig });
} catch (err) {
setError(
err instanceof Error ? err : new Error('Failed to fetch client config'),
);
} finally {
setLoading(false);
}
}, []);
return {
data,
loading,
error,
fetchClientConfig,
refetchClientConfig: fetchClientConfig,
};
};

View File

@ -1,163 +0,0 @@
import {
clearClientConfigCache,
getClientConfig,
refreshClientConfig,
} from '../clientConfigUtils';
import { REACT_APP_SERVER_BASE_URL } from '~/config';
global.fetch = jest.fn();
const mockClientConfig = {
billing: {
isBillingEnabled: true,
billingUrl: 'https://billing.example.com',
trialPeriods: [],
},
authProviders: {
google: true,
magicLink: false,
password: true,
microsoft: false,
sso: [],
},
signInPrefilled: false,
isMultiWorkspaceEnabled: true,
isEmailVerificationRequired: false,
defaultSubdomain: 'app',
frontDomain: 'localhost',
debugMode: true,
support: {
supportDriver: 'none',
supportFrontChatId: undefined,
},
sentry: {
environment: 'development',
release: '1.0.0',
dsn: undefined,
},
captcha: {
provider: undefined,
siteKey: undefined,
},
chromeExtensionId: undefined,
api: {
mutationMaximumAffectedRecords: 100,
},
isAttachmentPreviewEnabled: true,
analyticsEnabled: false,
canManageFeatureFlags: true,
publicFeatureFlags: [],
isMicrosoftMessagingEnabled: false,
isMicrosoftCalendarEnabled: false,
isGoogleMessagingEnabled: false,
isGoogleCalendarEnabled: false,
isConfigVariablesInDbEnabled: false,
};
describe('clientConfigUtils', () => {
beforeEach(() => {
clearClientConfigCache();
jest.clearAllMocks();
});
afterEach(() => {
clearClientConfigCache();
});
describe('getClientConfig', () => {
it('should fetch client config from API', async () => {
(fetch as jest.Mock).mockResolvedValueOnce({
ok: true,
json: async () => mockClientConfig,
});
const result = await getClientConfig();
expect(fetch).toHaveBeenCalledWith(
REACT_APP_SERVER_BASE_URL + '/client-config',
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
},
);
expect(result).toEqual(mockClientConfig);
});
it('should cache the result', async () => {
(fetch as jest.Mock).mockResolvedValueOnce({
ok: true,
json: async () => mockClientConfig,
});
// First call
await getClientConfig();
// Second call should use cache
const result = await getClientConfig();
expect(fetch).toHaveBeenCalledTimes(1);
expect(result).toEqual(mockClientConfig);
});
it('should handle fetch errors', async () => {
(fetch as jest.Mock).mockResolvedValueOnce({
ok: false,
status: 500,
statusText: 'Internal Server Error',
});
await expect(getClientConfig()).rejects.toThrow(
'Failed to fetch client config: 500 Internal Server Error',
);
});
});
describe('refreshClientConfig', () => {
it('should clear cache and fetch fresh data', async () => {
// First call to populate cache
(fetch as jest.Mock).mockResolvedValueOnce({
ok: true,
json: async () => mockClientConfig,
});
await getClientConfig();
// Mock a different response for refresh
const updatedConfig = { ...mockClientConfig, debugMode: false };
(fetch as jest.Mock).mockResolvedValueOnce({
ok: true,
json: async () => updatedConfig,
});
const result = await refreshClientConfig();
expect(fetch).toHaveBeenCalledTimes(2);
expect(result).toEqual(updatedConfig);
});
});
describe('clearClientConfigCache', () => {
it('should clear the cache', async () => {
// Populate cache
(fetch as jest.Mock).mockResolvedValueOnce({
ok: true,
json: async () => mockClientConfig,
});
await getClientConfig();
// Clear cache
clearClientConfigCache();
// Next call should fetch again
(fetch as jest.Mock).mockResolvedValueOnce({
ok: true,
json: async () => mockClientConfig,
});
await getClientConfig();
expect(fetch).toHaveBeenCalledTimes(2);
});
});
});

View File

@ -1,38 +0,0 @@
import { ClientConfig } from '~/generated/graphql';
import { REACT_APP_SERVER_BASE_URL } from '~/config';
let cachedClientConfig: ClientConfig | null = null;
export const getClientConfig = async (): Promise<ClientConfig> => {
if (cachedClientConfig !== null) {
return cachedClientConfig;
}
const response = await fetch(`${REACT_APP_SERVER_BASE_URL}/client-config`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
});
if (!response.ok) {
throw new Error(
`Failed to fetch client config: ${response.status} ${response.statusText}`,
);
}
const clientConfig: ClientConfig = await response.json();
cachedClientConfig = clientConfig;
return clientConfig;
};
export const refreshClientConfig = async (): Promise<ClientConfig> => {
cachedClientConfig = null;
return getClientConfig();
};
export const clearClientConfigCache = (): void => {
cachedClientConfig = null;
};

View File

@ -1,5 +1,6 @@
import { useLingui } from '@lingui/react/macro';
import { GET_CLIENT_CONFIG } from '@/client-config/graphql/queries/getClientConfig';
import { GET_DATABASE_CONFIG_VARIABLE } from '@/settings/admin-panel/config-variables/graphql/queries/getDatabaseConfigVariable';
import { SnackBarVariant } from '@/ui/feedback/snack-bar-manager/components/SnackBar';
import { useSnackBar } from '@/ui/feedback/snack-bar-manager/hooks/useSnackBar';
@ -47,6 +48,9 @@ export const useConfigVariableActions = (variableName: string) => {
query: GET_DATABASE_CONFIG_VARIABLE,
variables: { key: variableName },
},
{
query: GET_CLIENT_CONFIG,
},
],
});
} else {
@ -60,6 +64,9 @@ export const useConfigVariableActions = (variableName: string) => {
query: GET_DATABASE_CONFIG_VARIABLE,
variables: { key: variableName },
},
{
query: GET_CLIENT_CONFIG,
},
],
});
}
@ -89,6 +96,9 @@ export const useConfigVariableActions = (variableName: string) => {
query: GET_DATABASE_CONFIG_VARIABLE,
variables: { key: variableName },
},
{
query: GET_CLIENT_CONFIG,
},
],
});
} catch (error) {