import axios from 'axios' ; import { useQuery , useInfiniteQuery , UseInfiniteQueryOptions , UseQueryOptions , } from 'react-query' ; import { EntityKey , EntityKeys , formatGraphQuery , formatGraphResponse , GraphQueryOpts , InfiniteGraphQueryOpts , SubgraphEntities , SubgraphError , SubgraphQueryReturnTypes , } from '../utils/graph' ; const subgraphUrl = process . env . REACT_APP_SUBGRAPH_URL ; type GraphResult < E extends EntityKey , K extends EntityKeys < E > [ ] > = { [ PropertyKey in K [ number ] ] : SubgraphEntities [ E ] [ PropertyKey ] ; } [ ] ; export default function useSubgraphQuery < E extends EntityKey , K extends EntityKeys < E > > ( opts , reactQueryOptions ? ) { if ( ! subgraphUrl ) { throw new Error ( 'env.REACT_APP_SUBGRAPH_URL is missing' ) ; } return useQuery < GraphResult < E , K [ ] > , Error , GraphResult < E , K [ ] > , readonly [ string , GraphQueryOpts < E , K > | null ] > ( [ 'subgraph-query' , opts ] , async ( ) => { if ( ! opts ) return [ ] ; const response = await axios . post < { errors ? : SubgraphError [ ] ; data : SubgraphQueryReturnTypes [ E ] ; } > ( subgraphUrl , { query : formatGraphQuery ( opts ) , } , { headers : { 'Content-Type' : 'application/json' } } ) ; if ( 'errors' in response . data ) { throw new Error ( response . data . errors ?. [ 0 ] ?. message || 'Something is wrong with this Graph request' ) ; } return formatGraphResponse ( opts . entity , response . data ?. data ) ; } , { staleTime : 60000 , ... reactQueryOptions , } ) ; } export function useInfiniteSubgraphQuery < E extends EntityKey , K extends EntityKeys < E > > ( opts , reactQueryOptions ? ) { if ( ! subgraphUrl ) { throw new Error ( 'env.REACT_APP_SUBGRAPH_URL is missing' ) ; } return useInfiniteQuery < GraphResult < E , K [ ] > , Error , GraphResult < E , K [ ] > , readonly [ string , InfiniteGraphQueryOpts < E , K > ] > ( [ 'infinite-subgraph-query' , opts ] as const , async ( { queryKey , pageParam = 0 } ) => { const { pageSize , ... evaluatedOpts } = queryKey [ 1 ] ; const response = await axios . post < { errors ? : SubgraphError [ ] ; data : SubgraphQueryReturnTypes [ E ] ; } > ( subgraphUrl , { query : formatGraphQuery ( { ... evaluatedOpts , skip : pageSize * pageParam , first : pageSize , } ) , } , { headers : { 'Content-Type' : 'application/json' } } ) ; if ( 'errors' in response . data ) { throw new Error ( response . data . errors ?. [ 0 ] ?. message || 'Something is wrong with this Graph request' ) ; } return formatGraphResponse ( opts . entity , response . data ?. data ) ; } , { staleTime : 60000 , ... reactQueryOptions , getNextPageParam : ( lastPage , allPages ) => { if ( lastPage . length < opts . pageSize ) { return false ; } else { return allPages . length ; } } , } ) ; }