import fetch from 'isomorphic-unfetch' ; import { Store , Environment , RecordSource , DefaultHandlerProvider , Network } from 'relay-runtime' ; import { HandlerProvider } from 'relay-runtime/lib/handlers/RelayDefaultHandlerProvider' ; import { update } from './connection' ; let relayEnvironment ; function sleep ( ms ) { return new Promise ( ( resolve ) => setTimeout ( resolve , ms ) ) ; } function fetchQuery ( operation , variables , _cacheConfig , _uploadables ) { const endpoint = 'http://localhost:3000/graphql' ; return sleep ( 500 ) . then ( ( ) => fetch ( endpoint , { method : 'POST' , headers : { Accept : 'application/json' , 'Content-Type' : 'application/json' , } , body : JSON . stringify ( { query : operation . text , variables , } ) , } ) . then ( ( response ) => response . json ( ) ) ) ; } type InitProps = { records ? : any ; } ; const network = Network . create ( fetchQuery ) ; const handlerProvider = ( handle ) => { if ( handle === 'connection_table' ) return { update } ; return DefaultHandlerProvider ( handle ) ; } ; function createEnvironment ( records ) { const recordSource = new RecordSource ( records ) ; const store = new Store ( recordSource ) ; const environment = new Environment ( { network , store , handlerProvider , } ) ; return environment ; } export function initEnvironment ( options = { } ) { const { records = { } } = options ; if ( typeof window === 'undefined' ) { return createEnvironment ( records ) ; } if ( ! relayEnvironment ) { relayEnvironment = createEnvironment ( records ) ; } return relayEnvironment ; }