-
Notifications
You must be signed in to change notification settings - Fork 954
Expand file tree
/
Copy pathgraphql.ui.runtime.tsx
More file actions
202 lines (168 loc) · 6.19 KB
/
graphql.ui.runtime.tsx
File metadata and controls
202 lines (168 loc) · 6.19 KB
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
import type { ReactNode } from 'react';
import React from 'react';
import { UIRuntime } from '@teambit/ui';
import { BatchHttpLink } from '@apollo/client/link/batch-http';
import { InMemoryCache, ApolloClient, ApolloLink, HttpLink, createHttpLink } from '@apollo/client';
import type { DefaultOptions, NormalizedCacheObject, Operation } from '@apollo/client';
import { WebSocketLink } from '@apollo/client/link/ws';
import { onError } from '@apollo/client/link/error';
import { getMainDefinition } from '@apollo/client/utilities';
import type { OperationDefinitionNode } from 'graphql';
import crossFetch from 'cross-fetch';
import { createSplitLink } from './create-link';
import { GraphQLProvider } from './graphql-provider';
import { GraphqlAspect } from './graphql.aspect';
import { GraphqlRenderPlugins } from './render-lifecycle';
import { logError } from './logging';
/**
* Type of gql client.
* Used to abstract Apollo client, so consumers could import the type from graphql.ui, and not have to depend on @apollo/client directly
* */
export type GraphQLClient<T> = ApolloClient<T>;
type ClientOptions = {
/** Preset in-memory cache with state (e.g. continue state from SSR) */
state?: NormalizedCacheObject;
/** endpoint for websocket connections */
subscriptionUri?: string;
/** host extension id (workspace or scope). Used to configure the client */
host?: string;
};
export type GraphQLConfig = {
enableBatching?: boolean;
batchInterval?: number;
batchMax?: number;
};
export class GraphqlUI {
constructor(readonly config: GraphQLConfig = {}) {}
createClient(uri: string, { state, subscriptionUri, host }: ClientOptions = {}) {
const defaultOptions: DefaultOptions | undefined =
host === 'teambit.workspace/workspace'
? {
query: {
fetchPolicy: 'network-only',
},
watchQuery: {
fetchPolicy: 'network-only',
},
mutate: {
fetchPolicy: 'network-only',
},
}
: undefined;
const client = new ApolloClient({
link: this.createLink(uri, { subscriptionUri }),
cache: this.createCache({ state }),
defaultOptions,
});
return client;
}
createSsrClient({ serverUrl, headers }: { serverUrl: string; headers: any }) {
if (this.config.enableBatching) {
return this.createSsrClientBatched({ serverUrl, headers });
}
const link = ApolloLink.from([
onError(logError),
createHttpLink({
credentials: 'include',
uri: serverUrl,
headers,
fetch: crossFetch,
}),
]);
const client = new ApolloClient({
ssrMode: true,
link,
cache: this.createCache(),
});
return client;
}
private createSsrClientBatched({ serverUrl, headers }: { serverUrl: string; headers: any }) {
const batchedHttpLink = new BatchHttpLink({
uri: serverUrl,
credentials: 'include',
batchInterval: this.config.batchInterval,
batchMax: this.config.batchMax,
headers,
fetch: crossFetch,
});
const unbatchedHttpLink = new HttpLink({
uri: serverUrl,
credentials: 'include',
headers,
fetch: crossFetch,
});
const httpLink = ApolloLink.split(this.isMutation, unbatchedHttpLink, batchedHttpLink);
return new ApolloClient({
ssrMode: true,
link: ApolloLink.from([onError(logError), httpLink]),
cache: this.createCache(),
});
}
private createCache({ state }: { state?: NormalizedCacheObject } = {}) {
const cache = new InMemoryCache({
typePolicies: {
// The Aspect type has an `id` field (the aspect ID, e.g. "teambit.envs/envs").
// Without this, Apollo normalizes all Aspect objects by __typename:id, causing
// every component to share a single cache entry per aspect ID. This means the
// last-written aspect data overwrites all others (e.g. all components show the
// same env). Disabling normalization stores aspects inline per component.
Aspect: { keyFields: false },
},
});
if (state) cache.restore(state);
return cache;
}
private readonly isMutation = (op: Operation) => {
const def = getMainDefinition(op.query) as OperationDefinitionNode;
return def.kind === 'OperationDefinition' && def.operation === 'mutation';
};
private createLink(uri: string, { subscriptionUri }: { subscriptionUri?: string } = {}) {
if (this.config.enableBatching) {
return this.createLinkBatched(uri, { subscriptionUri });
}
const httpLink = new HttpLink({ credentials: 'include', uri });
const subsLink = subscriptionUri
? new WebSocketLink({
uri: subscriptionUri,
options: { reconnect: true },
})
: undefined;
const hybridLink = subsLink ? createSplitLink(httpLink, subsLink) : httpLink;
const errorLogger = onError(logError);
return ApolloLink.from([errorLogger, hybridLink]);
}
private createLinkBatched(uri: string, { subscriptionUri }: { subscriptionUri?: string } = {}) {
const batchedHttpLink = new BatchHttpLink({
uri,
credentials: 'include',
batchInterval: this.config.batchInterval,
batchMax: this.config.batchMax,
});
const unbatchedHttpLink = new HttpLink({
uri,
credentials: 'include',
});
const httpLink = ApolloLink.split(this.isMutation, unbatchedHttpLink, batchedHttpLink);
const wsLink = subscriptionUri
? new WebSocketLink({ uri: subscriptionUri, options: { reconnect: true } })
: undefined;
const transport = wsLink ? createSplitLink(httpLink, wsLink) : httpLink;
return ApolloLink.from([onError(logError), transport]);
}
getProvider = ({ client, children }: { client: GraphQLClient<any>; children: ReactNode }) => {
return <GraphQLProvider client={client}>{children}</GraphQLProvider>;
};
readonly renderPlugins = new GraphqlRenderPlugins(this);
static runtime = UIRuntime;
static dependencies = [];
static slots = [];
static defaultConfig: GraphQLConfig = {
enableBatching: false,
batchInterval: 50,
batchMax: 20,
};
static async provider(_, config: GraphQLConfig) {
return new GraphqlUI(config);
}
}
GraphqlAspect.addRuntime(GraphqlUI);