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

View File

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

View File

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

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 * as Apollo from '@apollo/client';
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<{
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'];
}>;
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`
fragment TradeFields on Trade {
@ -28,8 +28,6 @@ export const TradeFieldsFragmentDoc = gql`
createdAt
market {
id
decimalPlaces
positionDecimalPlaces
}
}
`;
@ -83,55 +81,37 @@ export function useTradesLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<Tra
export type TradesQueryHookResult = ReturnType<typeof useTradesQuery>;
export type TradesLazyQueryHookResult = ReturnType<typeof useTradesLazyQuery>;
export type TradesQueryResult = Apollo.QueryResult<TradesQuery, TradesQueryVariables>;
export const TradesSubDocument = gql`
subscription TradesSub($marketId: ID!) {
export const TradesUpdateDocument = gql`
subscription TradesUpdate($marketId: ID!) {
trades(marketId: $marketId) {
id
marketId
buyOrder
sellOrder
buyerId
sellerId
aggressor
price
size
createdAt
type
buyerFee {
makerFee
infrastructureFee
liquidityFee
}
sellerFee {
makerFee
infrastructureFee
liquidityFee
}
buyerAuctionBatch
sellerAuctionBatch
marketId
}
}
`;
/**
* __useTradesSubSubscription__
* __useTradesUpdateSubscription__
*
* To run a query within a React component, call `useTradesSubSubscription` 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
* To run a query within a React component, call `useTradesUpdateSubscription` and pass it any options that fit your needs.
* 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.
*
* @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
* const { data, loading, error } = useTradesSubSubscription({
* const { data, loading, error } = useTradesUpdateSubscription({
* variables: {
* marketId: // value for 'marketId'
* },
* });
*/
export function useTradesSubSubscription(baseOptions: Apollo.SubscriptionHookOptions<TradesSubSubscription, TradesSubSubscriptionVariables>) {
export function useTradesUpdateSubscription(baseOptions: Apollo.SubscriptionHookOptions<TradesUpdateSubscription, TradesUpdateSubscriptionVariables>) {
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 TradesSubSubscriptionResult = Apollo.SubscriptionResult<TradesSubSubscription>;
export type TradesUpdateSubscriptionHookResult = ReturnType<typeof useTradesUpdateSubscription>;
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 { TradesTable } from './trades-table';
import type { Trade, TradeEdge } from './trades-data-provider';
import type { TradesVariables } from './__generated__/Trades';
import type { TradesQueryVariables } from './__generated___/Trades';
interface TradesContainerProps {
marketId: string;
@ -22,7 +22,7 @@ export const TradesContainer = ({ marketId }: TradesContainerProps) => {
const newRows = useRef(0);
const scrolledToTop = useRef(true);
const variables = useMemo<TradesVariables>(
const variables = useMemo<TradesQueryVariables>(
() => ({ marketId, maxTrades: MAX_TRADES }),
[marketId]
);
@ -42,7 +42,13 @@ export const TradesContainer = ({ marketId }: TradesContainerProps) => {
}, []);
const update = useCallback(
({ data, delta }: { data: (TradeEdge | null)[]; delta: Trade[] }) => {
({
data,
delta,
}: {
data: (TradeEdge | null)[] | null;
delta: Trade[];
}) => {
if (!gridRef.current?.api) {
return false;
}
@ -70,7 +76,7 @@ export const TradesContainer = ({ marketId }: TradesContainerProps) => {
data,
totalCount,
}: {
data: (TradeEdge | null)[];
data: (TradeEdge | null)[] | null;
totalCount?: number;
}) => {
dataRef.current = data;

View File

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

View File

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