forked from vercel/next.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
relay.js
50 lines (43 loc) · 1.66 KB
/
relay.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import { useMemo } from 'react'
import { Environment, Network, RecordSource, Store } from 'relay-runtime'
let relayEnvironment
// Define a function that fetches the results of an operation (query/mutation/etc)
// and returns its results as a Promise
function fetchQuery(operation, variables, cacheConfig, uploadables) {
return fetch(process.env.NEXT_PUBLIC_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())
}
function createEnvironment(initialRecords) {
return new Environment({
// Create a network layer from the fetch function
network: Network.create(fetchQuery),
store: new Store(new RecordSource()),
})
}
export function initEnvironment(initialRecords) {
// Create a network layer from the fetch function
const environment = relayEnvironment ?? createEnvironment(initialRecords)
// If your page has Next.js data fetching methods that use Relay, the initial records
// will get hydrated here
if (initialRecords) {
environment.getStore().publish(new RecordSource(initialRecords))
}
// For SSG and SSR always create a new Relay environment
if (typeof window === 'undefined') return environment
// Create the Relay environment once in the client
if (!relayEnvironment) relayEnvironment = environment
return relayEnvironment
}
export function useEnvironment(initialRecords) {
const store = useMemo(() => initEnvironment(initialRecords), [initialRecords])
return store
}