Skip to content
This repository has been archived by the owner on Feb 16, 2024. It is now read-only.

Commit

Permalink
Merge branch 'main' of github.com:deriv-com/smarttrader into niloo/WE…
Browse files Browse the repository at this point in the history
…BREL-1602/server-time
  • Loading branch information
niloofar-deriv committed Nov 21, 2023
2 parents 5564108 + 20ea06c commit be37c9f
Show file tree
Hide file tree
Showing 11 changed files with 178 additions and 25 deletions.
2 changes: 1 addition & 1 deletion src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import ErrorBoundary from 'Components/common/error-boundary';
import Layout from 'Components/layout';
import Layout from 'Components/layout/Layout';

const App = () => (
<ErrorBoundary>
Expand Down
3 changes: 2 additions & 1 deletion src/api/hooks/useAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { useCallback } from 'react';

import type {
TSocketEndpointNames,
TSocketError,
TSocketPaginateableEndpointNames,
TSocketRequestPayload,
TSocketResponseData,
Expand Down Expand Up @@ -36,7 +37,7 @@ const useAPI = () => {
): {
subscribe: (
onData: (response: Promise<TSocketResponseData<T>>) => void,
onError: (response: Promise<TSocketResponseData<T>>) => void
onError: (response: Promise<TSocketError<T>>) => void
) => { unsubscribe?: VoidFunction };
} => socketConnection?.subscribe({ [name]: 1, subscribe: 1, ...(payload || {}) }),
[socketConnection]
Expand Down
23 changes: 23 additions & 0 deletions src/api/hooks/useActiveSymbols.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { useMemo } from 'react';
import useQuery from './useQuery';
import useLogin from './useLogin';

const useActiveSymbols = () => {
const { isLoggedIn, isAuthorized } = useLogin();
const { data: activeSymbols, ...rest } = useQuery('active_symbols', {
payload: { active_symbols: 'brief' },
options: { enabled: isLoggedIn ? isAuthorized : true },
});

const modifiedActiveSymbols = useMemo(
() => ({ ...activeSymbols?.active_symbols }),
[activeSymbols?.active_symbols]
);

return {
data: modifiedActiveSymbols,
...rest,
};
};

export default useActiveSymbols;
8 changes: 4 additions & 4 deletions src/api/hooks/useLogin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ import { useEffect, useMemo } from 'react';
const useLogin = () => {
const search = window.location.search;
const client_account_params = readLoginQueryParams();
const { data: client_info } = useAuthorize();
let is_logged_in = false;
const { data: client_info, isSuccess } = useAuthorize();
let isLoggedIn = false;

if (localStorage.getItem('active_loginId')) {
is_logged_in = true;
isLoggedIn = true;
}

const client_object = useMemo(() => {
Expand All @@ -25,7 +25,7 @@ const useLogin = () => {
if (search) deleteQueryParams();
}
}, [client_info, client_account_params, client_object, search]);
return { is_logged_in };
return { isLoggedIn, isAuthorized: isSuccess };
};

export default useLogin;
66 changes: 66 additions & 0 deletions src/api/hooks/useSubscription.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import useAPI from './useAPI';
import type {
TSocketAcceptableProps,
TSocketError,
TSocketRequestPayload,
TSocketResponseData,
TSocketSubscribableEndpointNames,
} from '../types';

const useSubscription = <T extends TSocketSubscribableEndpointNames>(name: T) => {
const [isLoading, setIsLoading] = useState(false);
const [isSubscribed, setIsSubscribed] = useState(false);
const [error, setError] = useState<TSocketError<T>>();
const [data, setData] = useState<TSocketResponseData<T>>();
const subscriber = useRef<{ unsubscribe?: VoidFunction }>();
const { subscribe: _subscribe } = useAPI();

const subscribe = useCallback(
(...props: TSocketAcceptableProps<T>) => {
const prop = props?.[0];
const payload = prop && 'payload' in prop ? (prop.payload as TSocketRequestPayload<T>) : undefined;

setIsLoading(true);
setIsSubscribed(true);

try {
subscriber.current = _subscribe(name, payload).subscribe(
async response => {
setData(await response);
setIsLoading(false);
},
async response => {
setError((await response).error as unknown as TSocketError<T>);
setIsLoading(false);
}
);
} catch (e) {
setError(e as TSocketError<T>);
}
},
[_subscribe, name]
);

const unsubscribe = useCallback(() => {
subscriber.current?.unsubscribe?.();
setIsSubscribed(false);
}, []);

useEffect(() => {
return () => {
unsubscribe();
};
}, [unsubscribe]);

return {
subscribe,
unsubscribe,
isLoading,
isSubscribed,
error,
data,
};
};

export default useSubscription;
37 changes: 37 additions & 0 deletions src/api/hooks/useTicksHistory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { useCallback } from 'react';
import useSubscription from './useSubscription';

import { TSocketRequestPayload } from 'Api/types';

type TTicksHistoryPayload = TSocketRequestPayload<'ticks_history'>['payload'];

const useTicksHistory = () => {
const { subscribe: _subscribe, unsubscribe, data, ...rest } = useSubscription('ticks_history');

const subscribe = useCallback(
(symbol: TTicksHistoryPayload['ticks_history'], granularity: TTicksHistoryPayload['granularity']) => {
const style: TTicksHistoryPayload['style'] = granularity ? 'candles' : 'ticks';

return _subscribe({
payload: {
adjust_start_time: 1,
ticks_history: symbol,
end: 'latest',
count: 1000,
granularity: granularity || undefined,
style,
},
});
},
[_subscribe]
);

return {
subscribe,
unsubscribe,
data,
...rest,
};
};

export default useTicksHistory;
26 changes: 25 additions & 1 deletion src/api/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -589,7 +589,7 @@ type TSocketEndpoints = {
response: StatesListResponse;
};
ticks_history: {
request: TicksHistoryRequest;
request: Omit<TicksHistoryRequest, 'count'> & { count?: number | string }; // count type from @deriv-api is wrong. Hence redefinition.
response: TicksHistoryResponse;
};
ticks: {
Expand Down Expand Up @@ -731,3 +731,27 @@ export type TSocketPaginateableEndpointNames = KeysMatching<
TSocketEndpoints,
{ request: { limit?: number; offset?: number } }
>;

export type TSocketError<T extends TSocketEndpointNames> = {
/**
* Echo of the request made.
*/
echo_req: {
[k: string]: unknown;
};
/**
* Error object.
*/
error: {
code: string;
message: string;
};
/**
* Action name of the request made.
*/
msg_type: T;
/**
* [Optional] Used to map request to response.
*/
req_id?: number;
};
15 changes: 15 additions & 0 deletions src/components/layout/Layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Fragment, PropsWithChildren } from 'react';
import Header from './header';
import Footer from './footer';

const Layout = ({ children }: PropsWithChildren) => {
return (
<Fragment>
<Header />
{children}
<Footer />
</Fragment>
);
};

export default Layout;
6 changes: 3 additions & 3 deletions src/components/layout/header/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import SectionTab from './SectionTab';

const Header = () => {
//logic for uselogin to be changed to add listener to storage
const { is_logged_in } = useLogin();
const { isLoggedIn } = useLogin();

return (
<div className='border-section-1 flex h-12 w-full flex-row items-center justify-between border-b'>
Expand All @@ -16,10 +16,10 @@ const Header = () => {
</div>
<div className='flex flex-row sm:hidden xs:hidden'>
<PlatformSwitcher />
{is_logged_in && <SectionTab />}
{isLoggedIn && <SectionTab />}
</div>
</div>
<div className='flex h-full items-center'>{is_logged_in ? <LoggedInState /> : <LoggedOutState />}</div>
<div className='flex h-full items-center'>{isLoggedIn ? <LoggedInState /> : <LoggedOutState />}</div>
</div>
);
};
Expand Down
4 changes: 2 additions & 2 deletions src/components/layout/header/__test__/Header.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,14 @@ jest.mock('react-i18next', () => ({
describe('Header', () => {
const useLoginSpy = jest.spyOn(useLoginHooks, 'default');
it('should render the component', () => {
useLoginSpy.mockReturnValue({ is_logged_in: false });
useLoginSpy.mockReturnValue({ isLoggedIn: false, isAuthorized: true });
render(<Header />);
expect(screen.getByText('SmartTrader')).toBeInTheDocument();
expect(screen.getByText('Log in')).toBeInTheDocument();
expect(screen.getByText('Sign up')).toBeInTheDocument();
});
it('should render the layout in the logged in state', () => {
useLoginSpy.mockReturnValue({ is_logged_in: true });
useLoginSpy.mockReturnValue({ isLoggedIn: true, isAuthorized: true });
render(<Header />);
expect(screen.getByText('Deposit')).toBeInTheDocument();
});
Expand Down
13 changes: 0 additions & 13 deletions src/components/layout/index.tsx

This file was deleted.

0 comments on commit be37c9f

Please sign in to comment.