Chore/move trade queries to graphql files (#1598)

* chore: move trade queries to graphql file

* chore: change default base for affected to develop
This commit is contained in:
Bartłomiej Głownia 2022-10-04 11:03:39 +02:00 committed by GitHub
parent 406b69566f
commit ae4960f700
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 77 additions and 297 deletions

View File

@ -1,12 +1,11 @@
import merge from 'lodash/merge'; import merge from 'lodash/merge';
import type { PartialDeep } from 'type-fest'; import type { PartialDeep } from 'type-fest';
import type { import type { TradesQuery, TradeFieldsFragment } from '@vegaprotocol/trades';
Trades,
Trades_market_tradesConnection_edges_node,
} from '@vegaprotocol/trades';
export const generateTrades = (override?: PartialDeep<Trades>): Trades => { export const generateTrades = (
const trades: Trades_market_tradesConnection_edges_node[] = [ override?: PartialDeep<TradesQuery>
): TradesQuery => {
const trades: TradeFieldsFragment[] = [
{ {
id: 'FFFFBC80005C517A10ACF481F7E6893769471098E696D0CC407F18134044CB16', id: 'FFFFBC80005C517A10ACF481F7E6893769471098E696D0CC407F18134044CB16',
price: '17116898', price: '17116898',
@ -41,7 +40,7 @@ export const generateTrades = (override?: PartialDeep<Trades>): Trades => {
__typename: 'Trade', __typename: 'Trade',
}, },
]; ];
const defaultResult: Trades = { const defaultResult: TradesQuery = {
market: { market: {
id: 'market-0', id: 'market-0',
tradesConnection: { tradesConnection: {

View File

@ -1,3 +1,2 @@
export * from './lib/trades-container'; export * from './lib/trades-container';
export * from './lib/__generated__/Trades'; export * from './lib/__generated___/Trades';
export * from './lib/__generated__/TradesSub';

View File

@ -5,8 +5,6 @@ fragment TradeFields on Trade {
createdAt createdAt
market { market {
id id
decimalPlaces
positionDecimalPlaces
} }
} }
@ -30,30 +28,12 @@ query Trades($marketId: ID!, $pagination: Pagination) {
} }
} }
subscription TradesSub($marketId: ID!) { subscription TradesUpdate($marketId: ID!) {
trades(marketId: $marketId) { trades(marketId: $marketId) {
id id
marketId
buyOrder
sellOrder
buyerId
sellerId
aggressor
price price
size size
createdAt createdAt
type marketId
buyerFee {
makerFee
infrastructureFee
liquidityFee
}
sellerFee {
makerFee
infrastructureFee
liquidityFee
}
buyerAuctionBatch
sellerAuctionBatch
} }
} }

View File

@ -1,107 +0,0 @@
/* tslint:disable */
/* eslint-disable */
// @generated
// This file was automatically generated and should not be edited.
import { Pagination } from "@vegaprotocol/types";
// ====================================================
// GraphQL query operation: Trades
// ====================================================
export interface Trades_market_tradesConnection_edges_node_market {
__typename: "Market";
/**
* Market ID
*/
id: string;
}
export interface Trades_market_tradesConnection_edges_node {
__typename: "Trade";
/**
* The hash of the trade data
*/
id: string;
/**
* The price of the trade (probably initially the passive order price, other determination algorithms are possible though) (uint64)
*/
price: string;
/**
* The number of units traded, will always be <= the remaining size of both orders immediately before the trade (uint64)
*/
size: string;
/**
* RFC3339Nano time for when the trade occurred
*/
createdAt: string;
/**
* The market the trade occurred on
*/
market: Trades_market_tradesConnection_edges_node_market;
}
export interface Trades_market_tradesConnection_edges {
__typename: "TradeEdge";
/**
* The trade
*/
node: Trades_market_tradesConnection_edges_node;
/**
* The cursor for this trade
*/
cursor: string;
}
export interface Trades_market_tradesConnection_pageInfo {
__typename: "PageInfo";
/**
* The first cursor in the current page
*/
startCursor: string;
/**
* The last cursor in the current page
*/
endCursor: string;
/**
* The connection has more pages to fetch when traversing forward through the connection
*/
hasNextPage: boolean;
/**
* The connection has more pages to fetch when traversing backward through the connection
*/
hasPreviousPage: boolean;
}
export interface Trades_market_tradesConnection {
__typename: "TradeConnection";
/**
* The trade in this connection
*/
edges: Trades_market_tradesConnection_edges[];
/**
* The pagination information
*/
pageInfo: Trades_market_tradesConnection_pageInfo;
}
export interface Trades_market {
__typename: "Market";
/**
* Market ID
*/
id: string;
tradesConnection: Trades_market_tradesConnection | null;
}
export interface Trades {
/**
* An instrument that is trading on the Vega network
*/
market: Trades_market | null;
}
export interface TradesVariables {
marketId: string;
pagination?: Pagination | null;
}

View File

@ -1,43 +0,0 @@
/* tslint:disable */
/* eslint-disable */
// @generated
// This file was automatically generated and should not be edited.
// ====================================================
// GraphQL subscription operation: TradesSub
// ====================================================
export interface TradesSub_trades {
__typename: "TradeUpdate";
/**
* The hash of the trade data
*/
id: string;
/**
* The price of the trade (probably initially the passive order price, other determination algorithms are possible though) (uint64)
*/
price: string;
/**
* The number of units traded, will always be <= the remaining size of both orders immediately before the trade (uint64)
*/
size: string;
/**
* RFC3339Nano time for when the trade occurred
*/
createdAt: string;
/**
* The market the trade occurred on
*/
marketId: string;
}
export interface TradesSub {
/**
* Subscribe to the trades updates
*/
trades: TradesSub_trades[] | null;
}
export interface TradesSubVariables {
marketId: string;
}

View File

@ -3,7 +3,7 @@ import { Schema as Types } from '@vegaprotocol/types';
import { gql } from '@apollo/client'; import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client'; import * as Apollo from '@apollo/client';
const defaultOptions = {} as const; const defaultOptions = {} as const;
export type TradeFieldsFragment = { __typename?: 'Trade', id: string, price: string, size: string, createdAt: string, market: { __typename?: 'Market', id: string, decimalPlaces: number, positionDecimalPlaces: number } }; export type TradeFieldsFragment = { __typename?: 'Trade', id: string, price: string, size: string, createdAt: string, market: { __typename?: 'Market', id: string } };
export type TradesQueryVariables = Types.Exact<{ export type TradesQueryVariables = Types.Exact<{
marketId: Types.Scalars['ID']; marketId: Types.Scalars['ID'];
@ -11,14 +11,14 @@ export type TradesQueryVariables = Types.Exact<{
}>; }>;
export type TradesQuery = { __typename?: 'Query', market?: { __typename?: 'Market', id: string, tradesConnection?: { __typename?: 'TradeConnection', edges: Array<{ __typename?: 'TradeEdge', cursor: string, node: { __typename?: 'Trade', id: string, price: string, size: string, createdAt: string, market: { __typename?: 'Market', id: string, decimalPlaces: number, positionDecimalPlaces: number } } }>, pageInfo: { __typename?: 'PageInfo', startCursor: string, endCursor: string, hasNextPage: boolean, hasPreviousPage: boolean } } | null } | null }; export type TradesQuery = { __typename?: 'Query', market?: { __typename?: 'Market', id: string, tradesConnection?: { __typename?: 'TradeConnection', edges: Array<{ __typename?: 'TradeEdge', cursor: string, node: { __typename?: 'Trade', id: string, price: string, size: string, createdAt: string, market: { __typename?: 'Market', id: string } } }>, pageInfo: { __typename?: 'PageInfo', startCursor: string, endCursor: string, hasNextPage: boolean, hasPreviousPage: boolean } } | null } | null };
export type TradesSubSubscriptionVariables = Types.Exact<{ export type TradesUpdateSubscriptionVariables = Types.Exact<{
marketId: Types.Scalars['ID']; marketId: Types.Scalars['ID'];
}>; }>;
export type TradesSubSubscription = { __typename?: 'Subscription', trades?: Array<{ __typename?: 'TradeUpdate', id: string, marketId: string, buyOrder: string, sellOrder: string, buyerId: string, sellerId: string, aggressor: Types.Side, price: string, size: string, createdAt: string, type: Types.TradeType, buyerAuctionBatch?: number | null, sellerAuctionBatch?: number | null, buyerFee: { __typename?: 'TradeFee', makerFee: string, infrastructureFee: string, liquidityFee: string }, sellerFee: { __typename?: 'TradeFee', makerFee: string, infrastructureFee: string, liquidityFee: string } }> | null }; export type TradesUpdateSubscription = { __typename?: 'Subscription', trades?: Array<{ __typename?: 'TradeUpdate', id: string, price: string, size: string, createdAt: string, marketId: string }> | null };
export const TradeFieldsFragmentDoc = gql` export const TradeFieldsFragmentDoc = gql`
fragment TradeFields on Trade { fragment TradeFields on Trade {
@ -28,8 +28,6 @@ export const TradeFieldsFragmentDoc = gql`
createdAt createdAt
market { market {
id id
decimalPlaces
positionDecimalPlaces
} }
} }
`; `;
@ -83,55 +81,37 @@ export function useTradesLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<Tra
export type TradesQueryHookResult = ReturnType<typeof useTradesQuery>; export type TradesQueryHookResult = ReturnType<typeof useTradesQuery>;
export type TradesLazyQueryHookResult = ReturnType<typeof useTradesLazyQuery>; export type TradesLazyQueryHookResult = ReturnType<typeof useTradesLazyQuery>;
export type TradesQueryResult = Apollo.QueryResult<TradesQuery, TradesQueryVariables>; export type TradesQueryResult = Apollo.QueryResult<TradesQuery, TradesQueryVariables>;
export const TradesSubDocument = gql` export const TradesUpdateDocument = gql`
subscription TradesSub($marketId: ID!) { subscription TradesUpdate($marketId: ID!) {
trades(marketId: $marketId) { trades(marketId: $marketId) {
id id
marketId
buyOrder
sellOrder
buyerId
sellerId
aggressor
price price
size size
createdAt createdAt
type marketId
buyerFee {
makerFee
infrastructureFee
liquidityFee
}
sellerFee {
makerFee
infrastructureFee
liquidityFee
}
buyerAuctionBatch
sellerAuctionBatch
} }
} }
`; `;
/** /**
* __useTradesSubSubscription__ * __useTradesUpdateSubscription__
* *
* To run a query within a React component, call `useTradesSubSubscription` and pass it any options that fit your needs. * To run a query within a React component, call `useTradesUpdateSubscription` and pass it any options that fit your needs.
* When your component renders, `useTradesSubSubscription` returns an object from Apollo Client that contains loading, error, and data properties * When your component renders, `useTradesUpdateSubscription` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI. * you can use to render your UI.
* *
* @param baseOptions options that will be passed into the subscription, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * @param baseOptions options that will be passed into the subscription, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
* *
* @example * @example
* const { data, loading, error } = useTradesSubSubscription({ * const { data, loading, error } = useTradesUpdateSubscription({
* variables: { * variables: {
* marketId: // value for 'marketId' * marketId: // value for 'marketId'
* }, * },
* }); * });
*/ */
export function useTradesSubSubscription(baseOptions: Apollo.SubscriptionHookOptions<TradesSubSubscription, TradesSubSubscriptionVariables>) { export function useTradesUpdateSubscription(baseOptions: Apollo.SubscriptionHookOptions<TradesUpdateSubscription, TradesUpdateSubscriptionVariables>) {
const options = {...defaultOptions, ...baseOptions} const options = {...defaultOptions, ...baseOptions}
return Apollo.useSubscription<TradesSubSubscription, TradesSubSubscriptionVariables>(TradesSubDocument, options); return Apollo.useSubscription<TradesUpdateSubscription, TradesUpdateSubscriptionVariables>(TradesUpdateDocument, options);
} }
export type TradesSubSubscriptionHookResult = ReturnType<typeof useTradesSubSubscription>; export type TradesUpdateSubscriptionHookResult = ReturnType<typeof useTradesUpdateSubscription>;
export type TradesSubSubscriptionResult = Apollo.SubscriptionResult<TradesSubSubscription>; export type TradesUpdateSubscriptionResult = Apollo.SubscriptionResult<TradesUpdateSubscription>;

View File

@ -9,7 +9,7 @@ import type { BodyScrollEvent, BodyScrollEndEvent } from 'ag-grid-community';
import { MAX_TRADES, tradesWithMarketProvider } from './trades-data-provider'; import { MAX_TRADES, tradesWithMarketProvider } from './trades-data-provider';
import { TradesTable } from './trades-table'; import { TradesTable } from './trades-table';
import type { Trade, TradeEdge } from './trades-data-provider'; import type { Trade, TradeEdge } from './trades-data-provider';
import type { TradesVariables } from './__generated__/Trades'; import type { TradesQueryVariables } from './__generated___/Trades';
interface TradesContainerProps { interface TradesContainerProps {
marketId: string; marketId: string;
@ -22,7 +22,7 @@ export const TradesContainer = ({ marketId }: TradesContainerProps) => {
const newRows = useRef(0); const newRows = useRef(0);
const scrolledToTop = useRef(true); const scrolledToTop = useRef(true);
const variables = useMemo<TradesVariables>( const variables = useMemo<TradesQueryVariables>(
() => ({ marketId, maxTrades: MAX_TRADES }), () => ({ marketId, maxTrades: MAX_TRADES }),
[marketId] [marketId]
); );
@ -42,7 +42,13 @@ export const TradesContainer = ({ marketId }: TradesContainerProps) => {
}, []); }, []);
const update = useCallback( const update = useCallback(
({ data, delta }: { data: (TradeEdge | null)[]; delta: Trade[] }) => { ({
data,
delta,
}: {
data: (TradeEdge | null)[] | null;
delta: Trade[];
}) => {
if (!gridRef.current?.api) { if (!gridRef.current?.api) {
return false; return false;
} }
@ -70,7 +76,7 @@ export const TradesContainer = ({ marketId }: TradesContainerProps) => {
data, data,
totalCount, totalCount,
}: { }: {
data: (TradeEdge | null)[]; data: (TradeEdge | null)[] | null;
totalCount?: number; totalCount?: number;
}) => { }) => {
dataRef.current = data; dataRef.current = data;

View File

@ -1,4 +1,3 @@
import { gql } from '@apollo/client';
import { import {
makeDataProvider, makeDataProvider,
makeDerivedDataProvider, makeDerivedDataProvider,
@ -8,69 +7,39 @@ import type { PageInfo } from '@vegaprotocol/react-helpers';
import type { Market } from '@vegaprotocol/market-list'; import type { Market } from '@vegaprotocol/market-list';
import { marketsProvider } from '@vegaprotocol/market-list'; import { marketsProvider } from '@vegaprotocol/market-list';
import type { import type {
Trades, TradesQuery,
Trades_market_tradesConnection_edges, TradeFieldsFragment,
Trades_market_tradesConnection_edges_node, TradesUpdateSubscription,
} from './__generated__/Trades'; } from './__generated___/Trades';
import type { TradesSub, TradesSub_trades } from './__generated__/TradesSub'; import { TradesDocument, TradesUpdateDocument } from './__generated___/Trades';
import orderBy from 'lodash/orderBy'; import orderBy from 'lodash/orderBy';
import produce from 'immer'; import produce from 'immer';
export const MAX_TRADES = 50; export const MAX_TRADES = 50;
export const TRADES_QUERY = gql` const getData = (
query Trades($marketId: ID!, $pagination: Pagination) { responseData: TradesQuery
market(id: $marketId) { ): ({
id cursor: string;
tradesConnection(pagination: $pagination) { node: TradeFieldsFragment;
edges { } | null)[] => responseData?.market?.tradesConnection?.edges || [];
node {
id
price
size
createdAt
market {
id
}
}
cursor
}
pageInfo {
startCursor
endCursor
hasNextPage
hasPreviousPage
}
}
}
}
`;
export const TRADES_SUB = gql` const getDelta = (subscriptionData: TradesUpdateSubscription) =>
subscription TradesSub($marketId: ID!) { subscriptionData?.trades || [];
trades(marketId: $marketId) {
id
price
size
createdAt
marketId
}
}
`;
const update = ( const update = (
data: (Trades_market_tradesConnection_edges | null)[], data: ReturnType<typeof getData>,
delta: TradesSub_trades[] delta: ReturnType<typeof getDelta>
) => { ) => {
return produce(data, (draft) => { return produce(data, (draft) => {
orderBy(delta, 'createdAt', 'desc').forEach((node) => { orderBy(delta, 'createdAt', 'desc').forEach((node) => {
if (!draft) {
return;
}
const index = draft.findIndex((edge) => edge?.node.id === node.id); const index = draft.findIndex((edge) => edge?.node.id === node.id);
if (index !== -1) { if (index !== -1) {
if (draft[index]?.node) { if (draft?.[index]?.node) {
Object.assign( Object.assign(draft[index]?.node as TradeFieldsFragment, node);
draft[index]?.node as Trades_market_tradesConnection_edges_node,
node
);
} }
} else { } else {
const firstNode = draft[0]?.node; const firstNode = draft[0]?.node;
@ -86,7 +55,6 @@ const update = (
}, },
}, },
cursor: '', cursor: '',
__typename: 'TradeEdge',
}); });
} }
} }
@ -94,29 +62,18 @@ const update = (
}); });
}; };
export type Trade = Omit< export type Trade = Omit<TradeFieldsFragment, 'market'> & { market?: Market };
Trades_market_tradesConnection_edges_node,
'market'
> & { market?: Market };
export type TradeEdge = { export type TradeEdge = {
cursor: Trades_market_tradesConnection_edges['cursor']; cursor: string;
node: Trade; node: Trade;
}; };
const getData = ( const getPageInfo = (responseData: TradesQuery): PageInfo | null =>
responseData: Trades
): Trades_market_tradesConnection_edges[] | null =>
responseData?.market?.tradesConnection?.edges || null;
const getDelta = (subscriptionData: TradesSub): TradesSub_trades[] =>
subscriptionData?.trades || [];
const getPageInfo = (responseData: Trades): PageInfo | null =>
responseData.market?.tradesConnection?.pageInfo || null; responseData.market?.tradesConnection?.pageInfo || null;
export const tradesProvider = makeDataProvider({ export const tradesProvider = makeDataProvider({
query: TRADES_QUERY, query: TradesDocument,
subscriptionQuery: TRADES_SUB, subscriptionQuery: TradesUpdateDocument,
update, update,
getData, getData,
getDelta, getDelta,
@ -132,16 +89,25 @@ export const tradesWithMarketProvider = makeDerivedDataProvider<
Trade[] Trade[]
>( >(
[tradesProvider, marketsProvider], [tradesProvider, marketsProvider],
(partsData): TradeEdge[] | null => (partsData): (TradeEdge | null)[] | null => {
(partsData[0] as ReturnType<typeof getData>)?.map((edge) => ({ const edges = partsData[0] as ReturnType<typeof getData>;
cursor: edge.cursor, return edges.map((edge) => {
node: { if (edge === null) {
return null;
}
const node = {
...edge.node, ...edge.node,
market: (partsData[1] as Market[]).find( market: (partsData[1] as Market[]).find(
(market) => market.id === edge.node.market.id (market) => market.id === edge.node.market.id
), ),
}, };
})) || null, const cursor = edge?.cursor || '';
return {
cursor,
node,
};
});
},
(parts): Trade[] | undefined => { (parts): Trade[] | undefined => {
if (!parts[0].isUpdate) { if (!parts[0].isUpdate) {
return; return;
@ -150,8 +116,8 @@ export const tradesWithMarketProvider = makeDerivedDataProvider<
return (parts[0].delta as ReturnType<typeof getDelta>).map( return (parts[0].delta as ReturnType<typeof getDelta>).map(
(deltaTrade) => ({ (deltaTrade) => ({
...((parts[0].data as ReturnType<typeof getData>)?.find( ...((parts[0].data as ReturnType<typeof getData>)?.find(
(trade) => trade.node.id === deltaTrade.id (edge) => edge?.node.id === deltaTrade.id
)?.node as Trades_market_tradesConnection_edges_node), )?.node as Trade),
market: (parts[1].data as Market[]).find( market: (parts[1].data as Market[]).find(
(market) => market.id === deltaTrade.marketId (market) => market.id === deltaTrade.marketId
), ),

View File

@ -1,7 +1,7 @@
{ {
"npmScope": "vegaprotocol", "npmScope": "vegaprotocol",
"affected": { "affected": {
"defaultBase": "master" "defaultBase": "develop"
}, },
"implicitDependencies": { "implicitDependencies": {
"package.json": { "package.json": {