@smartinvoicexyz/graphql
Version:
Unified source for helpers and schema used across the GraphQL services within the Smart Invoice protocol.
39 lines (38 loc) • 1.27 kB
JavaScript
import { ApolloClient, InMemoryCache, } from '@apollo/client';
import { graphUrls, isSupportedChainId, SUPPORTED_CHAIN_IDS, } from '@smartinvoicexyz/constants';
import { scalars } from './scalars';
import { decodeScalarsInResponse, } from './zeus';
import { Ops, ReturnTypes } from './zeus/const';
import { typedGql } from './zeus/typedDocumentNode';
const caches = SUPPORTED_CHAIN_IDS.reduce((o, chainId) => ({
...o,
[chainId]: new InMemoryCache(),
}), {});
export const getCache = (chainId) => caches[chainId];
const clients = SUPPORTED_CHAIN_IDS.reduce((o, chainId) => ({
...o,
[chainId]: new ApolloClient({
uri: graphUrls(chainId),
cache: caches[chainId],
}),
}), {});
export const fetchTypedQuery = (chainId) => async (o, ops) => {
if (!isSupportedChainId(chainId)) {
throw new Error(`Chain ${chainId} is not supported`);
}
const gql = typedGql('query', { scalars })(o, ops);
const { data, error } = await clients[chainId].query({
query: gql,
...ops,
});
if (error)
throw error;
return decodeScalarsInResponse({
response: data,
initialOp: 'query',
initialZeusQuery: o,
returns: ReturnTypes,
scalars,
ops: Ops,
});
};