import { GraphQLError } from 'graphql' import CustomGraphQLError from '../errors/customGraphQLError' import { HttpClient } from './HttpClient' import { inflightUrlWithQuery } from './middlewares/inflight' import { RequestConfig } from './typings' interface QueryOptions { query: string variables: Variables inflight?: boolean throwOnError?: boolean extensions?: Record } interface MutateOptions { mutate: string variables: Variables throwOnError?: boolean } export type Serializable = object | boolean | string | number export interface GraphQLResponse { data?: T errors?: GraphQLError[] extensions?: Record } const throwOnGraphQLErrors = (message: string, response: GraphQLResponse) => { if (response && response.errors && response.errors.length > 0) { throw new CustomGraphQLError(message, response.errors) } return response } export class GraphQLClient { constructor( private http: HttpClient ) {} public query = ( { query, variables, inflight, extensions, throwOnError }: QueryOptions, config: RequestConfig = {} ): Promise> => this.http.getWithBody>( config.url || '', { query, variables, extensions }, { inflightKey: inflight !== false ? inflightUrlWithQuery : undefined, ...config, }) .then(graphqlResponse => throwOnError === false ? graphqlResponse : throwOnGraphQLErrors(this.http.name, graphqlResponse) ) public mutate = ( { mutate, variables, throwOnError }: MutateOptions, config: RequestConfig = {} ) => this.http.post>( config.url || '', { query: mutate, variables }, config ) .then(graphqlResponse => throwOnError === false ? graphqlResponse : throwOnGraphQLErrors(this.http.name, graphqlResponse) ) }