import { FluentBundle } from "@fluent/bundle/compat" ; import { authMiddleware , cacheMiddleware , RelayNetworkLayer , RelayNetworkLayerResponse , RelayRequestAny , retryMiddleware , urlMiddleware , } from "react-relay-network-modern/es" ; import { GraphQLResponse , Observable , SubscribeFunction } from "relay-runtime" ; import { AccessTokenProvider } from "../auth" ; import clearHTTPCacheMiddleware from "./clearHTTPCacheMiddleware" ; import clientIDMiddleware from "./clientIDMiddleware" ; import { ManagedSubscriptionClient } from "./createManagedSubscriptionClient" ; import customErrorMiddleware from "./customErrorMiddleware" ; import persistedQueriesGetMethodMiddleware from "./persistedQueriesGetMethodMiddleware" ; export type TokenRefresh = ( req : RelayRequestAny , res : RelayNetworkLayerResponse ) => string | Promise < string > ; function createSubscriptionFunction ( subscriptionClient ) { const fn = ( operation , variables , cacheConfig ) => { return Observable . create < GraphQLResponse > ( ( sink ) => { const subscription = subscriptionClient . subscribe ( operation as any , variables , { force : cacheConfig . force === null ? undefined : cacheConfig . force , poll : cacheConfig . poll === null ? undefined : cacheConfig . poll , } , { onNext : sink . next , onError : sink . error , onCompleted : sink . complete , } ) ; return ( ) => { subscription . dispose ( ) ; } ; } ) ; } ; return fn ; } export default function createNetwork ( graphqlURL , subscriptionClient , clientID , accessTokenProvider , localeBundles , tokenRefresh ? , clearCacheBefore ? ) { return new RelayNetworkLayer ( [ clearHTTPCacheMiddleware ( clearCacheBefore ) , customErrorMiddleware ( localeBundles ) , cacheMiddleware ( { size : 100 , ttl : 30 * 1000 , clearOnMutation : true , } ) , urlMiddleware ( { url : ( ) => Promise . resolve ( graphqlURL ) , } ) , retryMiddleware ( { fetchTimeout : 15000 , retryDelays : ( attempt ) => Math . pow ( 2 , attempt + 4 ) * 100 , statusCodes : [ 500 , 503 , 504 ] , beforeRetry : ( { abort , attempt , lastError } ) => { if ( attempt > 2 ) { let message = lastError ?. message ; if ( message && lastError ?. name !== "RRNLRetryMiddlewareError" ) { message = `(${ lastError ?. name }) ${ message }` ; } abort ( message ) ; } } , } ) , authMiddleware ( { token : ( ) => { return accessTokenProvider ( ) || "" ; } , tokenRefreshPromise : tokenRefresh , allowEmptyToken : true , } ) , clientIDMiddleware ( clientID ) , persistedQueriesGetMethodMiddleware , ] , { subscribeFn : createSubscriptionFunction ( subscriptionClient ) as any } ) ; }