2017-08-14 16:41:12 +00:00
|
|
|
import { Environment, Network, RecordSource, Store } from 'relay-runtime'
|
2017-11-04 14:05:16 +00:00
|
|
|
import fetch from 'isomorphic-unfetch'
|
2017-08-14 16:41:12 +00:00
|
|
|
|
|
|
|
let relayEnvironment = null
|
|
|
|
|
|
|
|
// Define a function that fetches the results of an operation (query/mutation/etc)
|
|
|
|
// and returns its results as a Promise:
|
|
|
|
function fetchQuery (
|
2017-08-15 05:50:56 +00:00
|
|
|
operation,
|
|
|
|
variables,
|
|
|
|
cacheConfig,
|
2018-08-20 06:31:24 +00:00
|
|
|
uploadables
|
2017-08-14 16:41:12 +00:00
|
|
|
) {
|
|
|
|
return fetch(process.env.RELAY_ENDPOINT, {
|
|
|
|
method: 'POST',
|
|
|
|
headers: {
|
|
|
|
'Accept': 'application/json',
|
|
|
|
'Content-Type': 'application/json'
|
|
|
|
}, // Add authentication and other headers here
|
|
|
|
body: JSON.stringify({
|
|
|
|
query: operation.text, // GraphQL text from input
|
|
|
|
variables
|
|
|
|
})
|
|
|
|
}).then(response => response.json())
|
|
|
|
}
|
|
|
|
|
|
|
|
export default function initEnvironment ({ records = {} } = {}) {
|
2017-08-15 05:50:56 +00:00
|
|
|
// Create a network layer from the fetch function
|
2017-08-14 16:41:12 +00:00
|
|
|
const network = Network.create(fetchQuery)
|
|
|
|
const store = new Store(new RecordSource(records))
|
|
|
|
|
2017-08-15 05:50:56 +00:00
|
|
|
// Make sure to create a new Relay environment for every server-side request so that data
|
|
|
|
// isn't shared between connections (which would be bad)
|
2017-08-14 16:41:12 +00:00
|
|
|
if (!process.browser) {
|
|
|
|
return new Environment({
|
|
|
|
network,
|
|
|
|
store
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2017-08-15 05:50:56 +00:00
|
|
|
// reuse Relay environment on client-side
|
2017-08-14 16:41:12 +00:00
|
|
|
if (!relayEnvironment) {
|
|
|
|
relayEnvironment = new Environment({
|
|
|
|
network,
|
|
|
|
store
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
return relayEnvironment
|
|
|
|
}
|