Repository navigation
Expand file tree
/
Copy pathGraphiQL.fs
More file actions
303 lines (281 loc) · 11.2 KB
/
Copy pathGraphiQL.fs
File metadata and controls
303 lines (281 loc) · 11.2 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
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
module FSharp.Data.GraphQL.Samples.MagicEightBall.GraphiQL
open Suave
open Suave.Http
open Suave.Operators
// `GraphQL.Server.Ui.GraphiQL` (used by the other samples) only ships an ASP.NET Core middleware, so it can't be
// composed into a Suave `WebPart`. Its `GraphiQLPageModel.Render()` method produces static HTML for a fixed set of
// options (GraphQL endpoint `/`, subscriptions endpoint `/ws`, `graphql-ws` subscriptions), so that output is
// hardcoded here instead of invoking the internal renderer through reflection.
let private page =
"""<!--
* Copyright (c) 2024 GraphQL Contributors
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
-->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
body {
height: 100%;
margin: 0;
width: 100%;
overflow: hidden;
}
#graphiql {
height: 100vh;
}
</style>
<!--
This GraphiQL example depends on Promise and fetch, which are available in
modern browsers, but can be "polyfilled" for older browsers.
GraphiQL itself depends on React DOM.
If you do not want to rely on a CDN, you can host these files locally or
include them directly in your favored resource bunder.
-->
<script
src="https://cdn.jsdelivr.net/npm/whatwg-fetch@2.0.3/fetch.min.js"
integrity="sha384-dcF7KoWRaRpjcNbVPUFgatYgAijf8DqW6NWuqLdfB5Sb4Cdbb8iHX7bHsl9YhpKa"
crossorigin="anonymous"
></script>
<script
src="https://unpkg.com/react@16.14.0/umd/react.production.min.js"
integrity="sha384-N7y5SSAooNlIfb9H750GR82ufkn1JXJFaCjg8pmt+OZuKcZoTvTGfog4d4taG/cF"
crossorigin="anonymous"
></script>
<script
src="https://unpkg.com/react-dom@16.14.0/umd/react-dom.production.min.js"
integrity="sha384-j7WmMv3OO6n8pZRATOsaMVEdZcHpoaTBIika/l92YM2AkEex72QunlTQlgmu+pI8"
crossorigin="anonymous"
></script>
<!--
These two files can be found in the npm module, however you may wish to
copy them directly into your environment, or perhaps include them in your
favored resource bundler.
-->
<link
rel="stylesheet"
href="https://unpkg.com/graphiql@3.2.0/graphiql.min.css"
integrity="sha384-yz3/sqpuplkA7msMo0FE4ekg0xdwdvZ8JX9MVZREsxipqjU4h8IRfmAMRcb1QpUy"
crossorigin="anonymous"
/>
<script
src="https://unpkg.com/subscriptions-transport-ws@0.8.2/browser/client.js"
integrity="sha384-Eqe2SG8kA+Au+rwrgfWJ+epqYAtKGW/As+WdcywebVKX7377xelWa+/il4CHiHXI"
crossorigin="anonymous"
></script>
<script
src="https://unpkg.com/graphiql-subscriptions-fetcher@0.0.2/browser/client.js"
integrity="sha384-ArTEHLNWIe9TuoDpFEtD/NeztNdWn3SdmWwMiAuZaSJeOaYypEGzeQoBxuPO+ORM"
crossorigin="anonymous"
></script>
<script
src="https://unpkg.com/graphql-ws@5.16.0/umd/graphql-ws.min.js"
integrity="sha384-oEPbisbEBMo7iCrbQcKx244HXUjGnF1jyS8hkVZ3oCwnw9c9oLfY70c1RKeKj3+i"
crossorigin="anonymous"
></script>
</head>
<body>
<div id="graphiql">Loading...</div>
<script
src="https://unpkg.com/graphiql@3.2.0/graphiql.min.js"
type="application/javascript"
integrity="sha384-h7T8iQ4OYtRS2RIWfZ7ahqfNRtVrjc6Uz/gUJjydAV/uWn/HgC5GMnSKmsvNGeUH"
crossorigin="anonymous"
></script>
<script>
/**
* This GraphiQL example illustrates how to use some of GraphiQL's props
* in order to enable reading and updating the URL parameters, making
* link sharing of queries a little bit easier.
*
* This is only one example of this kind of feature, GraphiQL exposes
* various React params to enable interesting integrations.
*/
// Parse the search string to get url parameters.
var search = window.location.search;
var parameters = {};
search.substr(1).split('&').forEach(function (entry) {
var eq = entry.indexOf('=');
if (eq >= 0) {
parameters[decodeURIComponent(entry.slice(0, eq))] =
decodeURIComponent(entry.slice(eq + 1));
}
});
// if variables was provided, try to format it.
if (parameters.variables) {
try {
parameters.variables =
JSON.stringify(JSON.parse(parameters.variables), null, 2);
} catch (e) {
// Do nothing, we want to display the invalid JSON as a string, rather
// than present an error.
}
}
// When the query and variables string is edited, update the URL bar so
// that it can be easily shared
function onEditQuery(newQuery) {
parameters.query = newQuery;
updateURL();
}
function onEditVariables(newVariables) {
parameters.variables = newVariables;
updateURL();
}
function onEditOperationName(newOperationName) {
parameters.operationName = newOperationName;
updateURL();
}
function updateURL() {
var newSearch = '?' + Object.keys(parameters).filter(function (key) {
return Boolean(parameters[key]);
}).map(function (key) {
return encodeURIComponent(key) + '=' +
encodeURIComponent(parameters[key]);
}).join('&');
history.replaceState(null, null, newSearch);
}
// Defines a GraphQL fetcher using the fetch API. You're not required to
// use fetch, and could instead implement graphQLFetcher however you like,
// as long as it returns a Promise or Observable.
function graphQLFetcher(graphQLParams, fetcherOpts = { headers: {} }) {
// This example expects a GraphQL server at the path /graphql.
// Change this to point wherever you host your GraphQL server.
return fetch('/', {
method: 'post',
headers: Object.assign({"Accept":"application/json","Content-Type":"application/json"}, fetcherOpts.headers),
body: JSON.stringify(graphQLParams),
credentials: 'same-origin',
}).then(function (response) {
return response.text();
}).then(function (responseBody) {
try {
return JSON.parse(responseBody);
} catch (error) {
return responseBody;
}
});
}
function getSubscriptionsEndPoint() {
let subscriptionsEndPoint = "/ws";
if (/^(?:[a-z]+:)?\/\//i.test(subscriptionsEndPoint)) {
// if location includes protocol (e.g. "wss://") then return exact string
return subscriptionsEndPoint;
} else if (subscriptionsEndPoint[0] != '/') {
// if location is relative (e.g. "api") then prepend host and current path
let currentUrl = /^[^?]*(?=\/)/.exec(window.location.pathname);
currentUrl = currentUrl ? currentUrl[0] : '';
while (subscriptionsEndPoint.substring(0, 3) == '../') {
subscriptionsEndPoint = subscriptionsEndPoint.substring(3);
currentUrl = /^[^?]*(?=\/)/.exec(currentUrl);
currentUrl = currentUrl ? currentUrl[0] : '';
}
return (window.location.protocol === "http:" ? "ws://" : "wss://") + window.location.host + currentUrl + '/' + subscriptionsEndPoint;
}
// if location is absolute (e.g. "/api") then prepend host only
return (window.location.protocol === "http:" ? "ws://" : "wss://") + window.location.host + subscriptionsEndPoint;
}
const subscriptionEndPoint = getSubscriptionsEndPoint();
// Enable Subscriptions via WebSocket
let subscriptionsClient = null;
function subscriptionsTransportWsFetcher(graphQLParams, fetcherOpts = { headers: {} }) {
if (!subscriptionsClient)
subscriptionsClient = new window.SubscriptionsTransportWs.SubscriptionClient(subscriptionEndPoint, { reconnect: true });
return window.GraphiQLSubscriptionsFetcher.graphQLFetcher(subscriptionsClient, function (_graphQLParams) {
return graphQLFetcher(_graphQLParams, fetcherOpts);
})(graphQLParams);
}
function isSubscription(operationName, documentAST) {
if (!documentAST.definitions || !documentAST.definitions.length || !documentAST.definitions.filter) return false;
let definitions = documentAST.definitions.filter(function (def) { return def.kind === 'OperationDefinition'; });
if (operationName) definitions = definitions.filter(function (def) { return def.name && def.name.value === operationName; });
if (definitions.length === 0) return false;
return definitions[0].operation === 'subscription';
}
let wsClient = null;
function graphQLWsFetcher(payload, fetcherOpts) {
if (!fetcherOpts || !fetcherOpts.documentAST || !isSubscription(payload.operationName, fetcherOpts.documentAST))
return graphQLFetcher(payload, fetcherOpts);
if (!wsClient) {
wsClient = graphqlWs.createClient({ url: subscriptionEndPoint });
}
let deferred = null;
const pending = [];
let throwMe = null,
done = false;
const dispose = wsClient.subscribe(payload, {
next: (data) => {
pending.push(data);
if (deferred) deferred.resolve(false);
},
error: (err) => {
if (err instanceof Error) {
throwMe = err;
} else if (err instanceof CloseEvent) {
throwMe = new Error(`Socket closed with event ${err.code} ${err.reason || ""}`.trim());
} else {
// GraphQLError[]
throwMe = new Error(err.map(({ message }) => message).join(", "));
}
if (deferred) deferred.reject(throwMe);
},
complete: () => {
done = true;
if (deferred) deferred.resolve(true);
},
});
return {
[Symbol.asyncIterator]: function() {
return this;
},
next: function() {
if (done) return Promise.resolve({ done: true, value: undefined });
if (throwMe) return Promise.reject(throwMe);
if (pending.length) return Promise.resolve({ value: pending.shift() });
return new Promise(function(resolve, reject) {
deferred = { resolve, reject };
}).then(function(result) {
if (result) {
return { done: true, value: undefined };
} else {
return { value: pending.shift() };
}
});
},
return: function() {
dispose();
return Promise.resolve({ done: true, value: undefined });
}
};
}
const subscriptionFetcher = (true) ? graphQLWsFetcher : subscriptionsTransportWsFetcher;
// Render <GraphiQL /> into the body.
// See the README in the top level of this module to learn more about
// how you can customize GraphiQL by providing different values or
// additional child elements.
ReactDOM.render(
React.createElement(GraphiQL, {
fetcher: subscriptionFetcher,
query: parameters.query,
variables: parameters.variables,
operationName: parameters.operationName,
onEditQuery: onEditQuery,
onEditVariables: onEditVariables,
onEditOperationName: onEditOperationName,
isHeadersEditorEnabled: true,
}),
document.getElementById('graphiql'),
);
</script>
</body>
</html>
"""
/// <summary>A <see cref="Suave.Http.WebPart"/> that serves the GraphiQL IDE at <c>/graphiql</c>, pointed at the GraphQL API served at <c>/</c>.</summary>
let webPart : WebPart =
Filters.path "/graphiql"
>=> Filters.GET
>=> Writers.setMimeType "text/html; charset=utf-8"
>=> Successful.OK page