-
-
Save maraisr/32a7b0c1a464d52741729ced141065a9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
Environment, | |
FetchFunction, | |
Network, | |
RecordSource, | |
RequestParameters, | |
Store, | |
Variables, | |
} from 'relay-runtime'; | |
import fetch from 'isomorphic-unfetch'; | |
import { RecordMap } from 'relay-runtime/lib/store/RelayStoreTypes'; | |
const fetchQuery: FetchFunction = async ( | |
params: RequestParameters, | |
variables: Variables, | |
) => { | |
const response: Response = await fetch(`http://my-api.com/graph/graphql`, { | |
method: 'POST', | |
cache: 'no-cache', | |
headers: { | |
Accept: 'application/json', | |
'Content-Type': 'application/json', | |
}, | |
body: JSON.stringify({ | |
query: params.text, | |
variables, | |
doc_id: params.id, | |
}), | |
}); | |
const data = await response.json(); | |
const hasError = Array.isArray(data?.errors); | |
if (hasError) { | |
throw new GraphError(data.errors); | |
} | |
return data; | |
}; | |
const network = Network.create(fetchQuery); | |
const createEnvironment = (records: RecordMap = {}): Environment => { | |
const source = new RecordSource(records); | |
const store = new Store(source); | |
return new Environment({ | |
configName: 'standard', | |
network, | |
store, | |
}); | |
}; | |
let memoEnv: Environment = null; | |
export const getRelayEnvironment = (records: RecordMap = {}) => { | |
if (!process.browser) return createEnvironment(records); | |
if (memoEnv === null) { | |
memoEnv = createEnvironment(records); | |
} | |
return memoEnv; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment