-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathprepareData.js
53 lines (46 loc) · 1.51 KB
/
prepareData.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
51
52
53
import Relay from 'react-relay';
import toGraphQL from 'react-relay/lib/toGraphQL';
export default function prepareData(
{ Container, queryConfig },
networkLayer,
preloadedRequests = []
) {
return new Promise((resolve, reject) => {
const environment = new Relay.Environment();
const data = [];
const storeData = environment.getStoreData();
for (const { query, response } of preloadedRequests) {
storeData.handleQueryPayload(query, response);
data.push({ query: toGraphQL.Query(query), response });
}
environment.injectNetworkLayer({
sendMutation: networkLayer.sendMutation.bind(networkLayer),
supports: networkLayer.supports.bind(networkLayer),
sendQueries(requests) {
for (const request of requests) {
request.then(({ response }) => {
data.push({ query: toGraphQL.Query(request.getQuery()), response });
});
}
return networkLayer.sendQueries(requests);
},
});
const querySet = Relay.getQueries(Container, queryConfig);
environment.primeCache(querySet, onReadyStateChange);
function onReadyStateChange(readyState) {
if (readyState.error) {
reject(readyState.error);
} else if (readyState.aborted) {
reject(new Error('Aborted'));
} else if (readyState.done) {
const props = {
Container,
environment,
queryConfig,
initialReadyState: readyState,
};
resolve({ data, props });
}
}
});
}