-
Notifications
You must be signed in to change notification settings - Fork 821
/
environment.js
170 lines (158 loc) · 4.67 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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
import { Environment, RecordSource, Store } from 'relay-runtime';
// eslint-disable-next-line import/no-extraneous-dependencies
import { installRelayDevTools } from 'relay-devtools';
import { SubscriptionClient } from 'subscriptions-transport-ws';
import { execute } from 'apollo-link';
import { WebSocketLink } from 'apollo-link-ws';
import { Subject, timer } from 'rxjs';
import { debounce } from 'rxjs/operators';
import React, { Component } from 'react';
import {
commitMutation as CM,
QueryRenderer as QR,
requestSubscription as RS,
fetchQuery as FQ,
} from 'react-relay';
import * as PropTypes from 'prop-types';
import {
map, isEmpty, difference, filter, split, pathOr,
} from 'ramda';
import { urlMiddleware, RelayNetworkLayer } from 'react-relay-network-modern';
import uploadMiddleware from './uploadMiddleware';
// Dev tools
export const IN_DEV_MODE = process.env.NODE_ENV === 'development';
if (IN_DEV_MODE) installRelayDevTools();
// Service bus
const MESSENGER$ = new Subject().pipe(debounce(() => timer(500)));
export const MESSAGING$ = {
messages: MESSENGER$,
notifyError: (text) => MESSENGER$.next([{ type: 'error', text }]),
notifySuccess: (text) => MESSENGER$.next([{ type: 'message', text }]),
redirect: new Subject(),
};
// Default application exception.
export class ApplicationError extends Error {
constructor(errors) {
super();
this.data = errors;
}
}
// Get access providers from backend.
export const ACCESS_PROVIDERS = split(
',',
IN_DEV_MODE ? process.env.REACT_APP_ACCESS_PROVIDERS : window.ACCESS_PROVIDERS,
);
// Network
const envBasePath = isEmpty(window.BASE_PATH) || window.BASE_PATH.startsWith('/')
? window.BASE_PATH
: `/${window.BASE_PATH}`;
export const APP_BASE_PATH = IN_DEV_MODE ? '' : envBasePath;
// Subscription
let networkSubscriptions = null;
export const WS_ACTIVATED = IN_DEV_MODE
? process.env.REACT_APP_WS_ACTIVATED === 'true'
: window.WS_ACTIVATED === 'true';
if (WS_ACTIVATED) {
const loc = window.location;
const isSecure = loc.protocol === 'https:' ? 's' : '';
const subscriptionClient = new SubscriptionClient(
`ws${isSecure}://${loc.host}${APP_BASE_PATH}/graphql`,
{
reconnect: true,
},
);
const subscriptionLink = new WebSocketLink(subscriptionClient);
networkSubscriptions = (operation, variables) => execute(subscriptionLink, {
query: operation.text,
variables,
});
}
const network = new RelayNetworkLayer(
[
urlMiddleware({
url: `${APP_BASE_PATH}/graphql`,
credentials: 'same-origin',
}),
uploadMiddleware(),
],
{ subscribeFn: networkSubscriptions },
);
const store = new Store(new RecordSource());
// Activate the read from store then network
// store.holdGC();
export const environment = new Environment({
network,
store,
});
// Components
export class QueryRenderer extends Component {
render() {
const {
variables, query, render, managedErrorTypes,
} = this.props;
return (
<QR
environment={environment}
query={query}
variables={variables}
render={(data) => {
const { error } = data;
const types = error ? map((e) => e.name, error) : [];
const unmanagedErrors = difference(types, managedErrorTypes || []);
if (!isEmpty(unmanagedErrors)) throw new ApplicationError(error);
return render(data);
}}
/>
);
}
}
QueryRenderer.propTypes = {
managedErrorTypes: PropTypes.array,
variables: PropTypes.object,
render: PropTypes.func,
query: PropTypes.func,
};
// Relay functions
export const commitMutation = ({
mutation,
variables,
updater,
optimisticUpdater,
optimisticResponse,
onCompleted,
onError,
setSubmitting,
}) => CM(environment, {
mutation,
variables,
updater,
optimisticUpdater,
optimisticResponse,
onCompleted,
onError: (error) => {
if (setSubmitting) setSubmitting(false);
if (error && error.res && error.res.errors) {
const authRequired = filter(
(e) => e.data.type === 'authentication',
error.res.errors,
);
if (!isEmpty(authRequired)) {
MESSAGING$.redirect.next('/login');
} else {
const messages = map(
(e) => ({
type: 'error',
text: pathOr(e.message, ['data', 'details'], e),
}),
error.res.errors,
);
MESSAGING$.messages.next(messages);
if (onError) onError(error);
}
}
},
});
const deactivateSubscription = { dispose: () => undefined };
// eslint-disable-next-line max-len
export const requestSubscription = (args) => (WS_ACTIVATED ? RS(environment, args) : deactivateSubscription);
export const fetchQuery = (query, args) => FQ(environment, query, args);