-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenvironment.ts
62 lines (55 loc) · 1.49 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
import {
QueryResponseCache,
Network,
Environment,
Store,
RecordSource,
RequestParameters,
Variables,
} from "relay-runtime";
function createQueryCache() {
return new QueryResponseCache({ size: 10, ttl: 5000 });
}
function createNetwork(responseCache: QueryResponseCache) {
function fetchQuery(operation: RequestParameters, variables: Variables) {
return fetch("/api/graphql", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
query: operation.text,
variables: variables,
}),
}).then((response) => {
return response.json();
});
}
return Network.create((operation, variables) => {
const queryID = operation.id ?? operation.cacheID;
const fromQueryCache = responseCache.get(queryID, variables);
if (fromQueryCache) {
return fromQueryCache;
}
return fetchQuery(operation, variables);
});
}
const responseCacheByEnvironment = new WeakMap<
Environment,
QueryResponseCache
>();
export function getCacheByEnvironment(environment: Environment) {
return responseCacheByEnvironment.get(environment);
}
export function createEnvironment() {
const cache = createQueryCache();
const network = createNetwork(cache);
const store = new Store(new RecordSource());
const environment = new Environment({
network,
store,
isServer: typeof window === "undefined",
});
responseCacheByEnvironment.set(environment, cache);
return environment;
}