Skip to content

Instantly share code, notes, and snippets.

@enisdenjo
Last active August 30, 2023 12:07
Show Gist options
  • Save enisdenjo/d7bc1a013433502349d2763c3d2f2b79 to your computer and use it in GitHub Desktop.
Save enisdenjo/d7bc1a013433502349d2763c3d2f2b79 to your computer and use it in GitHub Desktop.
GraphiQL ❤️ graphql-sse
<!--
* Copyright (c) 2021 GraphQL Contributors
* All rights reserved.
*
* This code is licensed under the MIT license.
* Use it however you wish.
-->
<!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 AsyncIterator, 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
crossorigin
src="https://unpkg.com/react@16/umd/react.development.js"
></script>
<script
crossorigin
src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"
></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/graphiql.min.css" />
</head>
<body>
<div id="graphiql">Loading...</div>
<script
src="https://unpkg.com/graphiql/graphiql.js"
type="application/javascript"
></script>
<script
src="https://unpkg.com/graphql-sse/umd/graphql-sse.js"
type="application/javascript"
></script>
<script>
const sseClient = graphqlSse.createClient({
singleConnection: true, // or use false if you have a HTTP/2 server
url: "http://localhost:4000/graphql/stream",
retryAttempts: 0,
lazy: false, // connect as soon as the page opens
});
function subscribe(payload) {
let deferred = null;
const pending = [];
let throwMe = null,
done = false;
const dispose = sseClient.subscribe(payload, {
next: (data) => {
pending.push(data);
deferred?.resolve(false);
},
error: (err) => {
throwMe = err;
deferred?.reject(throwMe);
},
complete: () => {
done = true;
deferred?.resolve(true);
},
});
return {
[Symbol.asyncIterator]() {
return this;
},
async next() {
if (done) return { done: true, value: undefined };
if (throwMe) throw throwMe;
if (pending.length) return { value: pending.shift() };
return (await new Promise(
(resolve, reject) => (deferred = { resolve, reject })
))
? { done: true, value: undefined }
: { value: pending.shift() };
},
async return() {
dispose();
return { done: true, value: undefined };
},
};
}
ReactDOM.render(
React.createElement(GraphiQL, {
fetcher: subscribe,
defaultVariableEditorOpen: true,
}),
document.getElementById("graphiql")
);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment