-
Notifications
You must be signed in to change notification settings - Fork 737
/
Copy pathMiddlewareApp.tsx
534 lines (475 loc) · 14.7 KB
/
MiddlewareApp.tsx
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
import * as React from 'react'
import { Provider } from 'react-redux'
import createStore from '../createStore'
import Playground, { Playground as IPlayground } from './Playground'
import { Helmet } from 'react-helmet'
import * as fetch from 'isomorphic-fetch'
import { GraphQLConfig } from '../graphqlConfig'
import * as yaml from 'js-yaml'
import ProjectsSideNav from './ProjectsSideNav'
import {
styled,
ThemeProvider,
theme as styledTheme,
keyframes,
} from '../styled'
import OldThemeProvider from './Theme/ThemeProvider'
import { getActiveEndpoints } from './util'
import { ISettings } from '../types'
import PlaygroundStorage from './PlaygroundStorage'
import { mapKeys } from 'lodash'
import * as queryString from 'query-string'
const store = createStore()
export interface Props {
endpoint?: string
endpointUrl?: string
subscriptionEndpoint?: string
setTitle?: boolean
settings?: ISettings
folderName?: string
configString?: string
showNewWorkspace?: boolean
isElectron?: boolean
canSaveConfig?: boolean
onSaveConfig?: (configString: string) => void
onNewWorkspace?: () => void
getRef?: (ref: any) => void
session?: any
env?: any
config?: GraphQLConfig
configPath?: string
}
export interface State {
endpoint: string
subscriptionPrefix?: string
subscriptionEndpoint?: string
shareUrl?: string
settingsString: string
settings: ISettings
configIsYaml?: boolean
configString?: string
activeProjectName?: string
activeEnv?: string
headers?: any
}
const defaultSettings = `{
"general.betaUpdates": false,
"editor.theme": "dark",
"editor.reuseHeaders": true,
"request.credentials": "omit",
"tracing.hideTracingResponse": true
}`
export default class MiddlewareApp extends React.Component<Props, State> {
playground: IPlayground
constructor(props: Props) {
super(props)
;(global as any).m = this
let settingsString = localStorage.getItem('settings') || defaultSettings
settingsString = this.migrateSettingsString(settingsString)
const configIsYaml = props.configString
? this.isConfigYaml(props.configString)
: false
const { activeEnv, projectName } = this.getInitialActiveEnv(props.config)
const params = queryString.parse(location.search)
let headers
let endpoint =
props.endpoint ||
props.endpointUrl ||
params.endpoint ||
`${location.origin}${location.pathname}`
let subscriptionEndpoint: any =
props.subscriptionEndpoint || params.subscriptionEndpointndpoint
const paramHeaders = params.headers
if (paramHeaders) {
try {
headers = JSON.parse(paramHeaders)
} catch (e) {
//
}
}
if (props.configString && props.config && activeEnv) {
const endpoints = getActiveEndpoints(props.config, activeEnv, projectName)
endpoint = endpoints.endpoint
subscriptionEndpoint = endpoints.subscriptionEndpoint
headers = endpoints.headers
} else {
subscriptionEndpoint = this.getGraphcoolSubscriptionEndpoint(endpoint)
}
subscriptionEndpoint =
this.normalizeSubscriptionUrl(endpoint, subscriptionEndpoint) || undefined
this.removeLoader()
this.state = {
endpoint: this.absolutizeUrl(endpoint),
subscriptionEndpoint,
settingsString,
settings: this.props.settings || this.getSettings(settingsString),
configIsYaml,
configString: props.configString,
activeEnv,
activeProjectName: projectName,
headers,
}
}
removeLoader() {
const loadingWrapper = document.getElementById('loading-wrapper')
if (loadingWrapper) {
loadingWrapper.remove()
}
}
getGraphcoolSubscriptionEndpoint(endpoint) {
if (endpoint.includes('api.graph.cool')) {
return `wss://subscriptions.graph.cool/v1/${
endpoint.split('/').slice(-1)[0]
}`
}
return endpoint
}
migrateSettingsString(settingsString: string): string {
const defaultSettingsObject = JSON.parse(defaultSettings)
const replacementMap = {
theme: 'editor.theme',
reuseHeaders: 'editor.reuseHeaders',
}
try {
const currentSettings = JSON.parse(settingsString)
const settings = {
...defaultSettingsObject,
...mapKeys(currentSettings, (value, key) => replacementMap[key] || key),
}
return JSON.stringify(settings, null, 2)
} catch (e) {
//
}
return settingsString
}
componentWillReceiveProps(nextProps: Props) {
if (
nextProps.configString !== this.props.configString &&
nextProps.configString
) {
const configIsYaml = this.isConfigYaml(nextProps.configString)
this.setState({ configIsYaml })
}
}
getInitialActiveEnv(
config?: GraphQLConfig,
): { projectName?: string; activeEnv?: string } {
if (config) {
if (config.extensions && config.extensions.endpoints) {
return {
activeEnv: Object.keys(config.extensions.endpoints)[0],
}
}
if (config.projects) {
const projectName = Object.keys(config.projects)[0]
const project = config.projects[projectName]
if (project.extensions && project.extensions.endpoints) {
return {
activeEnv: Object.keys(project.extensions.endpoints)[0],
projectName,
}
}
}
}
return {}
}
isConfigYaml(configString: string) {
try {
yaml.safeLoad(configString)
return true
} catch (e) {
//
}
return false
}
absolutizeUrl(url) {
if (url.startsWith('/')) {
return location.origin + url
}
return url
}
normalizeSubscriptionUrl(endpoint, subscriptionEndpoint) {
if (subscriptionEndpoint) {
if (subscriptionEndpoint.startsWith('/')) {
const secure =
endpoint.includes('https') || location.href.includes('https')
? 's'
: ''
return `ws${secure}://${location.host}${subscriptionEndpoint}`
} else {
return subscriptionEndpoint.replace(/^http/, 'ws')
}
}
return endpoint.replace(/^http/, 'ws')
}
componentDidMount() {
if (this.state.subscriptionEndpoint === '') {
this.updateSubscriptionsUrl()
}
}
render() {
const title = this.props.setTitle ? (
<Helmet>
<title>{this.getTitle()}</title>
</Helmet>
) : null
const theme = this.state.settings['editor.theme']
return (
<div>
{title}
<Provider store={store}>
<ThemeProvider theme={{ ...styledTheme, mode: theme }}>
<OldThemeProvider theme={theme}>
<App>
{this.props.config &&
this.state.activeEnv && (
<ProjectsSideNav
config={this.props.config}
folderName={this.props.folderName || 'GraphQL App'}
theme={theme}
activeEnv={this.state.activeEnv}
onSelectEnv={this.handleSelectEnv}
onNewWorkspace={this.props.onNewWorkspace}
showNewWorkspace={Boolean(this.props.showNewWorkspace)}
isElectron={Boolean(this.props.isElectron)}
onEditConfig={this.handleStartEditConfig}
getSessionCount={this.getSessionCount}
activeProjectName={this.state.activeProjectName}
/>
)}
<Playground
endpoint={this.state.endpoint}
subscriptionsEndpoint={this.state.subscriptionEndpoint}
share={this.share}
shareUrl={this.state.shareUrl}
onChangeEndpoint={this.handleChangeEndpoint}
onChangeSubscriptionsEndpoint={
this.handleChangeSubscriptionsEndpoint
}
settings={this.normalizeSettings(this.state.settings)}
settingsString={this.state.settingsString}
onSaveSettings={this.handleSaveSettings}
onChangeSettings={this.handleChangeSettings}
getRef={this.getPlaygroundRef}
config={this.props.config!}
configString={this.state.configString!}
configIsYaml={this.state.configIsYaml!}
canSaveConfig={Boolean(this.props.canSaveConfig)}
onChangeConfig={this.handleChangeConfig}
onSaveConfig={this.handleSaveConfig}
onUpdateSessionCount={this.handleUpdateSessionCount}
fixedEndpoints={Boolean(this.state.configString)}
session={this.props.session}
headers={this.state.headers}
configPath={this.props.configPath}
/>
</App>
</OldThemeProvider>
</ThemeProvider>
</Provider>
</div>
)
}
handleUpdateSessionCount = () => {
this.forceUpdate()
}
getSessionCount = (endpoint: string): number => {
if (this.state.endpoint === endpoint && this.playground) {
return this.playground.state.sessions.length
}
return PlaygroundStorage.getSessionCount(endpoint)
}
getPlaygroundRef = ref => {
this.playground = ref
if (typeof this.props.getRef === 'function') {
this.props.getRef(ref)
}
}
handleStartEditConfig = () => {
this.playground.openConfigTab()
}
handleChangeConfig = (configString: string) => {
this.setState({ configString })
}
handleSaveConfig = () => {
/* tslint:disable-next-line */
console.log('handleSaveConfig called')
if (typeof this.props.onSaveConfig === 'function') {
/* tslint:disable-next-line */
console.log('calling this.props.onSaveConfig', this.state.configString)
this.props.onSaveConfig(this.state.configString!)
}
}
handleSelectEnv = (env: string, projectName?: string) => {
const { endpoint, subscriptionEndpoint, headers } = getActiveEndpoints(
this.props.config!,
env,
projectName,
)!
this.setState({
activeEnv: env,
endpoint,
headers,
subscriptionEndpoint,
activeProjectName: projectName,
})
}
private getSettings(settingsString = this.state.settingsString): ISettings {
try {
const settings = JSON.parse(settingsString)
return this.normalizeSettings(settings)
} catch (e) {
// ignore
}
return JSON.parse(defaultSettings)
}
private normalizeSettings(settings: ISettings) {
const theme = settings['editor.theme']
if (theme !== 'dark' && theme !== 'light') {
settings['editor.theme'] = 'dark'
}
return settings
}
private handleChangeSettings = (settingsString: string) => {
this.setState({ settingsString })
}
private handleSaveSettings = () => {
try {
const settings = JSON.parse(this.state.settingsString)
this.setState({ settings })
localStorage.setItem('settings', this.state.settingsString)
} catch (e) {
/* tslint:disable-next-line */
console.error(e)
}
}
private share = (session: any) => {
fetch('https://api.graph.cool/simple/v1/cj81hi46q03c30196uxaswrz2', {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: `
mutation ($session: String! $endpoint: String!) {
addSession(session: $session endpoint: $endpoint) {
id
}
}
`,
variables: {
session: JSON.stringify(session),
endpoint: this.normalizeEndpoint(this.state.endpoint),
},
}),
})
.then(res => res.json())
.then(res => {
const shareUrl = `https://graphqlbin.com/${res.data.addSession.id}`
// const shareUrl = `${location.origin}/${res.data.addSession.id}`
this.setState({ shareUrl })
})
}
private normalizeEndpoint(endpoint) {
if (!endpoint.match(/https?:\/\/(.*?)\//)) {
return location.origin + endpoint
} else {
return endpoint
}
}
private handleChangeEndpoint = endpoint => {
this.setState({ endpoint })
}
private handleChangeSubscriptionsEndpoint = subscriptionEndpoint => {
this.setState({ subscriptionEndpoint })
}
private getTitle() {
if (this.state.endpoint.includes('api.graph.cool')) {
const projectId = this.getProjectId(this.state.endpoint)
const cluster = this.state.endpoint.includes('api.graph.cool')
? 'shared'
: 'local'
return `${cluster}/${projectId} - Playground`
}
return `Playground - ${this.state.endpoint}`
}
private async updateSubscriptionsUrl() {
const candidates = this.getSubscriptionsUrlCandidated(this.state.endpoint)
const validCandidate = await find(candidates, candidate =>
this.wsEndpointValid(candidate),
)
if (validCandidate) {
this.setState({ subscriptionEndpoint: validCandidate })
}
}
private getSubscriptionsUrlCandidated(endpoint): string[] {
const candidates: string[] = []
candidates.push(endpoint.replace('https', 'wss').replace('http', 'ws'))
if (endpoint.includes('graph.cool')) {
candidates.push(
`wss://subscriptions.graph.cool/v1/${this.getProjectId(endpoint)}`,
)
}
if (endpoint.includes('/simple/v1/')) {
// it's a graphcool local endpoint
const host = endpoint.match(/https?:\/\/(.*?)\//)
candidates.push(
`ws://${host![1]}/subscriptions/v1/${this.getProjectId(endpoint)}`,
)
}
return candidates
}
private wsEndpointValid(url): Promise<boolean> {
return new Promise(resolve => {
const socket = new WebSocket(url, 'graphql-ws')
socket.addEventListener('open', event => {
socket.send(JSON.stringify({ type: 'connection_init' }))
})
socket.addEventListener('message', event => {
const data = JSON.parse(event.data)
if (data.type === 'connection_ack') {
resolve(true)
}
})
socket.addEventListener('error', event => {
resolve(false)
})
setTimeout(() => {
resolve(false)
}, 1000)
})
}
private getProjectId(endpoint) {
return endpoint.split('/').slice(-1)[0]
}
}
async function find(
iterable: any[],
predicate: (item?: any, index?: number) => Promise<boolean>,
): Promise<any | null> {
for (let i = 0; i < iterable.length; i++) {
const element = iterable[i]
const result = await predicate(element, i)
if (result) {
return element
}
}
return null
}
const appearIn = keyframes`
from {
opacity: 0;
transform: translateY(10px);
}
to {
opacity: 1;
transform: translateY(0);
}
`
const App = styled.div`
display: flex;
width: 100%;
opacity: 0;
transform: translateY(10px);
animation: ${appearIn} 0.5s ease-out forwards 0.2s;
`