This repository has been archived by the owner on Sep 2, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 35
/
Environment.js
94 lines (81 loc) · 2.3 KB
/
Environment.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// @flow
import { Environment, Network, RecordSource, Store } from 'relay-runtime';
import RelayQueryResponseCache from './RelayQueryResponseCache';
const cache = new RelayQueryResponseCache();
type GraphQLError = {|
message: string,
locations?: {|
line: number,
column: number,
|},
path?: string[],
_proxy?: {|
statusCode: number,
url: string,
|},
|};
export default function createEnvironment(
onPartialError: GraphQLError => void,
accessToken: string = '',
) {
const networkHeaders: Object = {
Accept: 'application/json',
'Content-Type': 'application/json',
};
if (accessToken) {
networkHeaders.authorization = accessToken;
}
const fetchQuery = async (operation, variables, cacheConfig) => {
const query = operation.text;
if (cacheConfig.force === true) {
await cache.remove(query, variables);
} else {
// refetch is not forced so try to find it in cache
const value = await cache.get(query, variables);
if (value !== null) {
// cache hit, yay
return value;
}
}
// TODO: fetch persisted queries instead (based on operation.id)
const jsonPayload = await (await fetch('https://beta-graphql.kiwi.com/', {
method: 'POST',
headers: networkHeaders,
body: JSON.stringify({
query: operation.text,
variables,
}),
})).json();
if (!jsonPayload.errors) {
// always save the valid response (probably not needed during cache "force")
await cache.set(query, variables, jsonPayload);
}
return jsonPayload;
};
return new PartialErrorsEnvironment(
{
network: Network.create(fetchQuery),
store: new Store(new RecordSource()),
},
onPartialError,
);
}
/**
* This environment is workaround for: https://github.com/facebook/relay/issues/1913
*/
class PartialErrorsEnvironment extends Environment {
onPartialError: GraphQLError => void;
constructor(config: Object, onPartialError: GraphQLError => void) {
super(config);
this.onPartialError = onPartialError;
}
execute = (executeConfig: Object) => {
return super.execute(executeConfig).do({
next: executePayload => {
if (executePayload.errors) {
executePayload.errors.map(error => this.onPartialError(error));
}
},
});
};
}