Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion packages/base/src/App.ce.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@ describe('test App ce', () => {
(useSelector as jest.Mock).mockImplementation((selector) => {
return selector({
user: {
token: 'AAh32ffdswt'
token: 'AAh32ffdswt',
isLoggingIn: false
},
nav: {
modalStatus: {
Expand Down
12 changes: 9 additions & 3 deletions packages/base/src/App.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,8 @@ describe('App', () => {
(useSelector as jest.Mock).mockImplementation((selector) => {
return selector({
user: {
token: 'AAh32ffdswt'
token: 'AAh32ffdswt',
isLoggingIn: false
},
nav: {
modalStatus: {
Expand Down Expand Up @@ -137,7 +138,8 @@ describe('App', () => {
(useSelector as jest.Mock).mockImplementation((selector) => {
return selector({
user: {
token: ''
token: '',
isLoggingIn: false
}
});
});
Expand Down Expand Up @@ -210,12 +212,16 @@ describe('App', () => {
(useSelector as jest.Mock).mockImplementation((selector) => {
return selector({
user: {
token: ''
token: '',
isLoggingIn: false
},
nav: {
modalStatus: {
[ModalName.Company_Notice]: false
}
},
availabilityZone: {
availabilityZoneTips: []
}
});
});
Expand Down
14 changes: 8 additions & 6 deletions packages/base/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,8 @@ export const Wrapper: React.FC<{
return <>{!initRenderApp && children}</>;
};
function App() {
const { token } = useSelector((state: IReduxState) => ({
token: state.user.token
const { isAfterLoggingIn } = useSelector((state: IReduxState) => ({
isAfterLoggingIn: !state.user.isLoggingIn && !!state.user.token
}));
const dispatch = useDispatch();
const { notificationContextHolder } = useNotificationContext();
Expand Down Expand Up @@ -160,7 +160,9 @@ function App() {
userOperationPermissions
]);
const elements = useRoutes(
token ? (AuthRouterConfigData as RouteObject[]) : unAuthRouterConfig
isAfterLoggingIn
? (AuthRouterConfigData as RouteObject[])
: unAuthRouterConfig
);
useChangeTheme();
const themeData = useMemo(() => {
Expand Down Expand Up @@ -204,10 +206,10 @@ function App() {
});
}, [dispatch, fetchModuleSupportStatus, getUserBySession, updateDriverList]);
useEffect(() => {
if (token) {
if (isAfterLoggingIn) {
getInitialData();
}
}, [token, getInitialData]);
}, [getInitialData, isAfterLoggingIn]);
useEffect(() => {
i18n.changeLanguage(currentLanguage);
}, [currentLanguage]);
Expand Down Expand Up @@ -314,7 +316,7 @@ function App() {
<StyledEngineProvider injectFirst>
<ThemeProvider theme={themeData}>
{notificationContextHolder}
<EmptyBox if={!!token} defaultNode={<>{elements}</>}>
<EmptyBox if={isAfterLoggingIn} defaultNode={<>{elements}</>}>
<ErrorBoundary>{body}</ErrorBoundary>
</EmptyBox>
</ThemeProvider>
Expand Down
100 changes: 100 additions & 0 deletions packages/base/src/hooks/useNavigateToWorkbench/index.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import { act, cleanup } from '@testing-library/react';
import { superRenderHook } from '@actiontech/shared/lib/testUtil/superRender';
import { useDispatch, useSelector } from 'react-redux';
import {
baseMockApi,
createSpySuccessResponse
} from '@actiontech/shared/lib/testUtil/mockApi';
import useNavigateToWorkbench from '.';
import { mockUseRecentlySelectedZone } from '../../testUtils/mockHooks/mockUseRecentlySelectedZone';
import { mockGatewayTipsData } from '@actiontech/shared/lib/testUtil/mockApi/base/gateway/data';

jest.mock('react-redux', () => ({
...jest.requireActual('react-redux'),
useDispatch: jest.fn(),
useSelector: jest.fn()
}));

describe('useNavigateToWorkbench', () => {
const dispatchSpy = jest.fn();
let getGatewayTipsSpy: jest.SpyInstance;
let getSQLQueryConfigurationSpy: jest.SpyInstance;

beforeEach(() => {
(useDispatch as jest.Mock).mockImplementation(() => dispatchSpy);
(useSelector as jest.Mock).mockImplementation((selector) => {
return selector({
availabilityZone: {
availabilityZoneTips: mockGatewayTipsData
}
});
});
mockUseRecentlySelectedZone();
getGatewayTipsSpy = baseMockApi.gateway.getGatewayTips();
getSQLQueryConfigurationSpy = baseMockApi.cloudBeaver.getSqlQueryUrl();
jest.useFakeTimers();
});

afterEach(() => {
jest.useRealTimers();
jest.clearAllMocks();
cleanup();
});

it('should initialize with correct default values', () => {
const { result } = superRenderHook(() => useNavigateToWorkbench());

expect(result.current.navigateToWorkbenchLoading).toBeFalsy();
expect(result.current.getAvailabilityZoneTipsLoading).toBeFalsy();
expect(typeof result.current.navigateToWorkbenchAsync).toBe('function');
expect(typeof result.current.getAvailabilityZoneTipsAsync).toBe('function');
});

it('should fetch availability zone tips successfully', async () => {
const { result } = superRenderHook(() => useNavigateToWorkbench());
expect(result.current.getAvailabilityZoneTipsLoading).toBeFalsy();

act(() => {
result.current.getAvailabilityZoneTipsAsync();
});
expect(result.current.getAvailabilityZoneTipsLoading).toBeTruthy();
await act(async () => jest.advanceTimersByTime(3000));
expect(result.current.getAvailabilityZoneTipsLoading).toBeFalsy();

expect(getGatewayTipsSpy).toHaveBeenCalledTimes(1);
expect(dispatchSpy).toHaveBeenCalledWith({
type: 'availabilityZone/updateAvailabilityZoneTips',
payload: { availabilityZoneTips: mockGatewayTipsData }
});
});

it('should fetch SQL query configuration successfully', async () => {
const mockUpdateRecentlySelectedZone = jest.fn();
getSQLQueryConfigurationSpy.mockImplementation(() =>
createSpySuccessResponse({
data: {
enable_sql_query: true,
sql_query_root_uri: '/cloudbeaver'
}
})
);
mockUseRecentlySelectedZone({
availabilityZone: undefined,
updateRecentlySelectedZone: mockUpdateRecentlySelectedZone
});
const { result } = superRenderHook(() => useNavigateToWorkbench());
expect(result.current.navigateToWorkbenchLoading).toBeFalsy();

act(() => {
result.current.navigateToWorkbenchAsync();
});
expect(result.current.navigateToWorkbenchLoading).toBeTruthy();
await act(async () => jest.advanceTimersByTime(3000));
expect(result.current.navigateToWorkbenchLoading).toBeFalsy();

expect(getSQLQueryConfigurationSpy).toHaveBeenCalledTimes(1);
expect(mockUpdateRecentlySelectedZone).toHaveBeenCalledWith(
mockGatewayTipsData[0]
);
});
});
86 changes: 86 additions & 0 deletions packages/base/src/hooks/useNavigateToWorkbench/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { useRequest } from 'ahooks';
import { useDispatch, useSelector } from 'react-redux';
import { DmsApi } from '@actiontech/shared/lib/api';
import { ResponseCode } from '@actiontech/dms-kit';
import useRecentlySelectedZone from '@actiontech/dms-kit/es/features/useRecentlySelectedZone';
import { IReduxState } from '../../store';
import { updateAvailabilityZoneTips } from '../../store/availabilityZone';

const useNavigateToWorkbench = () => {
const dispatch = useDispatch();

const availabilityZoneTips = useSelector(
(state: IReduxState) => state.availabilityZone.availabilityZoneTips
);

const { availabilityZone, updateRecentlySelectedZone } =
useRecentlySelectedZone();

const {
runAsync: getAvailabilityZoneTipsAsync,
loading: getAvailabilityZoneTipsLoading
} = useRequest(
() =>
DmsApi.GatewayService.GetGatewayTips().then((res) => {
if (res.data.code === ResponseCode.SUCCESS) {
return res.data.data;
}
return [];

Check warning on line 28 in packages/base/src/hooks/useNavigateToWorkbench/index.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🧾 Statement is not covered

Warning! Not covered statement
}),
{
onSuccess: (res) => {
dispatch(
updateAvailabilityZoneTips({
availabilityZoneTips: res ?? []

Check warning on line 34 in packages/base/src/hooks/useNavigateToWorkbench/index.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🌿 Branch is not covered

Warning! Not covered branch
})
);
},
manual: true
}
);

const {
loading: navigateToWorkbenchLoading,
runAsync: navigateToWorkbenchAsync
} = useRequest(
() => {
return DmsApi.CloudBeaverService.GetSQLQueryConfiguration().then(
(res) => {
if (res.data.code === ResponseCode.SUCCESS) {
return res.data.data;
}
}
);
},
{
manual: true,
onSuccess: (res) => {
if (
res?.enable_sql_query &&
res.sql_query_root_uri &&
res.sql_query_root_uri !== location.pathname
) {
// 如果当前设置了可用区 并且没有最近选择的可用区记录 则设置一个默认的可用区
if (!!availabilityZoneTips.length && !availabilityZone) {
updateRecentlySelectedZone(availabilityZoneTips[0]);
}

// res.sql_query_root_uri !== location.pathname 防止无限刷新
// 因为sql_query_root_uri是不携带origin的,只有pathname。所以开发环境localhost不可以直接跳转到CB
// #if [PROD]
window.location.href = res.sql_query_root_uri;
// #endif
}
}
}
);

return {
navigateToWorkbenchLoading,
navigateToWorkbenchAsync,
getAvailabilityZoneTipsAsync,
getAvailabilityZoneTipsLoading
};
};

export default useNavigateToWorkbench;
20 changes: 20 additions & 0 deletions packages/base/src/hooks/useSessionUser/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,24 @@ describe('useSessionUser', () => {
});
expect(result.current.getSessionUserLoading).toBeFalsy();
});

it('should get user system data', async () => {
const { result } = superRenderHook(() => useSessionUser(), undefined, {
initStore: {
user: { uid: 'test' }
}
});
expect(result.current.getSessionUserSystemLoading).toBeFalsy();
expect(result.current.shouldNavigateToWorkbench).toEqual(undefined);

await act(async () => {
result.current.getSessionUserInfoAsync();
await jest.advanceTimersByTime(3000);
});
expect(getUserBySessionSpy).toHaveBeenCalledTimes(1);
expect(getCurrentUserSpy).toHaveBeenCalledTimes(1);
await act(async () => jest.advanceTimersByTime(3000));
expect(result.current.getSessionUserSystemLoading).toBeFalsy();
expect(result.current.shouldNavigateToWorkbench).toBeFalsy();
});
});
28 changes: 27 additions & 1 deletion packages/base/src/hooks/useSessionUser/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { ResponseCode } from '@actiontech/dms-kit';
import { updateUserUid } from '../../store/user';
import { useUserInfo } from '@actiontech/shared/lib/features';
import Session from '@actiontech/shared/lib/api/base/service/Session';
import User from '@actiontech/shared/lib/api/base/service/User';
import { GetUserSystemEnum } from '@actiontech/shared/lib/api/base/service/common.enum';

const useSessionUser = () => {
const dispatch = useDispatch();
Expand All @@ -28,10 +30,34 @@ const useSessionUser = () => {
}
});

const {
data: shouldNavigateToWorkbench,
runAsync: getSessionUserInfoAsync,
loading: getSessionUserSystemLoading
} = useRequest(
() =>
Session.GetUserBySession({}).then((res) => {
if (res.data.code === ResponseCode.SUCCESS) {
const uid = res.data.data?.user_uid ?? '';
return User.GetUser({ user_uid: uid }).then((resp) => {
if (resp.data.code === ResponseCode.SUCCESS) {
return resp.data.data?.system === GetUserSystemEnum.WORKBENCH;
}
});
}
}),
{
manual: true
}
);

return {
sessionUser,
getSessionUserLoading,
getUserBySession
getUserBySession,
getSessionUserInfoAsync,
shouldNavigateToWorkbench,
getSessionUserSystemLoading
};
};

Expand Down
Loading