-
Notifications
You must be signed in to change notification settings - Fork 0
/
environment.ts
64 lines (53 loc) · 1.55 KB
/
environment.ts
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import { useMemo } from 'react';
import * as RelayRuntime from 'relay-runtime';
import {
Environment,
FetchFunction,
Network,
RecordSource,
Store,
} from 'relay-runtime';
import RelayModernEnvironment from 'relay-runtime/lib/store/RelayModernEnvironment';
import type { RecordMap } from 'relay-runtime/lib/store/RelayStoreTypes';
RelayRuntime.RelayFeatureFlags.ENABLE_RELAY_RESOLVERS = true;
let relayEnvironment: RelayModernEnvironment;
const fetchQuery: FetchFunction = (operation, variables) => {
return fetch(new URL('/api/graphql', 'http://localhost:3000'), {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: operation.text,
variables,
}),
}).then((response) => response.json());
};
const createRelayEnvironment = () => {
const environment = new Environment({
network: Network.create(fetchQuery),
store: new Store(new RecordSource()),
});
return environment;
};
const initEnvironment = (initialRecords?: RecordMap) => {
const environment = relayEnvironment ?? createRelayEnvironment();
if (initialRecords) {
environment.getStore().publish(new RecordSource(initialRecords));
}
if (typeof window === 'undefined') {
return environment;
}
if (!relayEnvironment) {
relayEnvironment = environment;
}
return relayEnvironment;
};
export const useEnvironment = (initialRecords?: RecordMap) => {
const store = useMemo(
() => initEnvironment(initialRecords),
[initialRecords],
);
return store;
};