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
133 lines (115 loc) · 3.85 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
// @flow
import { DeviceInfo } from '@kiwicom/mobile-localization';
import { Environment, Network, RecordSource, Store, Observable } from 'relay-runtime';
import fetchWithRetries from '@adeira/fetch';
// This works, and requires no native setup. Note that @sentry/node does not work since it relies on crypto module, which is not available in RN
// TODO: try to use rn-nodeify and react-native-crypt and use @sentry/node next time target-version changes
import * as Sentry from '@sentry/browser';
import { SENTRY_DSN } from 'react-native-dotenv';
import ConnectionManager from './ConnectionManager';
import CacheManager from './CacheManager';
type FetcherResponse = {|
+data: Object,
+errors?: $ReadOnlyArray<Object>,
|};
let useSentry;
const { NODE_ENV } = process.env;
try {
// The app will crash if SENTRY_DSN is wrong. Let's rather deactivate it if it for some reason is not set correctly
Sentry.init({ dsn: SENTRY_DSN, enabled: NODE_ENV !== 'development' });
useSentry = true;
} catch {
useSentry = false;
}
const logError = error => {
if (useSentry) {
Sentry.captureException(new Error(error.message));
}
};
const GRAPHQL_URL = 'https://graphql.kiwi.com/';
const store = new Store(new RecordSource());
async function fetchFromTheNetwork(networkHeaders, operation, variables, observer) {
try {
const fetchResponse = await fetchWithRetries(GRAPHQL_URL, {
method: 'POST',
headers: networkHeaders,
body: JSON.stringify({
query: operation.text, // TODO: fetch persisted queries instead (based on operation.id)
variables,
}),
fetchTimeout: 15000,
retryDelays: [1000, 3000],
});
const jsonResponse = await fetchResponse.json();
if (jsonResponse.errors) {
jsonResponse.errors.forEach(error => {
console.warn(error);
logError(error);
});
}
if (operation.operationKind !== 'mutation') {
CacheManager.set(operation.name, variables, jsonResponse);
}
observer.next(jsonResponse);
observer.complete();
} catch (error) {
// Handle error from fetch, unless we will see loader forever
observer.error(error);
observer.complete();
console.warn(error);
logError(error);
}
}
const handleNoNetworkNoCachedResponse = observer => {
// If not we are stuck on loader forever.
observer.error({ message: 'No network' });
observer.complete();
};
const asyncStoreRead = async (observer, operation, variables) => {
try {
const cachedData = await CacheManager.get(operation.name, variables);
if (cachedData) {
// It loads smoother if we do this in a set timeout
// If we don't the UI freezes for a while
setTimeout(() => {
observer.next(cachedData);
if (ConnectionManager.isConnected() === false) {
observer.complete();
}
});
} else if (ConnectionManager.isConnected() === false) {
handleNoNetworkNoCachedResponse(observer);
}
} catch (error) {
// AsyncStorage read wasn't successful - nevermind
console.warn('error', error);
}
};
export default function createEnvironment(
accessToken: string = '',
authHeaderKey: string = 'authorization',
) {
const networkHeaders: Object = {
Accept: 'application/json',
'Content-Type': 'application/json',
'Accept-Language': DeviceInfo.getLocaleUnderscored(),
'X-Client': 'mobile/rn',
};
if (accessToken) {
networkHeaders[authHeaderKey] = accessToken;
}
const fetchQuery = (operation, variables): Promise<FetcherResponse> => {
return Observable.create(observer => {
if (operation.operationKind !== 'mutation') {
asyncStoreRead(observer, operation, variables);
}
if (ConnectionManager.isConnected()) {
fetchFromTheNetwork(networkHeaders, operation, variables, observer);
}
});
};
return new Environment({
network: Network.create(fetchQuery),
store,
});
}