import { GraphQLClient } from 'graphql-request' ; import { ClientError } from 'graphql-request' ; import type { Variables } from 'graphql-request/dist/types' ; import type * as Dom from 'graphql-request/dist/types.dom' ; import { GQLError } from './GQLError' ; import type { IResponseInterceptor } from './IResponseInterceptor' ; export class CustomGraphQLClient extends GraphQLClient { get blockReason ( ) : Error | string | null { return this . requestsBlockedReason ; } private interceptors : IResponseInterceptor [ ] = [ ] ; private isRequestsBlocked = false ; private requestsBlockedReason : Error | string | null = null ; registerInterceptor ( interceptor ) { this . interceptors . push ( interceptor ) ; } request < T extends any , V = Variables > ( query , variables ? , requestHeaders ? ) { return this . interceptors . reduce ( ( accumulator , interceptor ) => interceptor ( accumulator ) , this . overrideRequest < T > ( query , variables , requestHeaders ) ) ; } enableRequests ( ) { this . isRequestsBlocked = false ; this . requestsBlockedReason = null ; } blockRequests ( reason ) { this . isRequestsBlocked = true ; this . requestsBlockedReason = reason ; } private blockRequestsReasonHandler ( ) { if ( this . isRequestsBlocked ) { if ( this . requestsBlockedReason instanceof Error ) { throw this . requestsBlockedReason ; } else { throw new Error ( this . requestsBlockedReason ?? undefined ) ; } } } private async overrideRequest < T > ( query , variables ? , requestHeaders ? ) { this . blockRequestsReasonHandler ( ) ; try { const response = await this . rawRequest < T > ( query , variables , requestHeaders ) ; return response . data as T ; } catch ( error ) { if ( isClientError ( error ) ) { throw new GQLError ( error ) ; } throw error ; } } } function isClientError ( obj ) { return obj instanceof ClientError || obj . response ; }