import { ApolloClient, NormalizedCacheObject, HttpLink, InMemoryCache, DocumentNode } from '@apollo/client' import fetch from 'cross-fetch' import { DataObjectDetailsFragment, GetDataObjectDetails, GetDataObjectDetailsQuery, GetDataObjectDetailsQueryVariables, DistirubtionBucketsWithObjectsFragment, GetDistributionBucketsWithObjectsQuery, GetDistributionBucketsWithObjectsQueryVariables, GetDistributionBucketsWithObjects, } from './generated/queries' import { Maybe } from './generated/schema' export class QueryNodeApi { private apolloClient: ApolloClient public constructor(endpoint: string) { this.apolloClient = new ApolloClient({ link: new HttpLink({ uri: endpoint, fetch }), cache: new InMemoryCache(), defaultOptions: { query: { fetchPolicy: 'no-cache', errorPolicy: 'all' } }, }) } // Get entity by unique input protected async uniqueEntityQuery< QueryT extends { [k: string]: Maybe> | undefined }, VariablesT extends Record >( query: DocumentNode, variables: VariablesT, resultKey: keyof QueryT ): Promise[keyof QueryT] | null> { return (await this.apolloClient.query({ query, variables })).data[resultKey] || null } // Get entities by "non-unique" input and return first result protected async firstEntityQuery< QueryT extends { [k: string]: unknown[] }, VariablesT extends Record >(query: DocumentNode, variables: VariablesT, resultKey: keyof QueryT): Promise { return (await this.apolloClient.query({ query, variables })).data[resultKey][0] || null } // Query-node: get multiple entities protected async multipleEntitiesQuery< QueryT extends { [k: string]: unknown[] }, VariablesT extends Record >(query: DocumentNode, variables: VariablesT, resultKey: keyof QueryT): Promise { return (await this.apolloClient.query({ query, variables })).data[resultKey] } public getDataObjectDetails(objectId: string): Promise { return this.uniqueEntityQuery( GetDataObjectDetails, { id: objectId }, 'storageDataObjectByUniqueInput' ) } public getDistributionBucketsWithObjects(ids: string[]): Promise { return this.multipleEntitiesQuery< GetDistributionBucketsWithObjectsQuery, GetDistributionBucketsWithObjectsQueryVariables >(GetDistributionBucketsWithObjects, { ids }, 'distributionBuckets') } }