Skip to content

feat: add explorer and exporter plugins #1626

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 5, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
<!--
* Copyright (c) 2021 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>
<html lang="en_US">

<head>
<meta charset=utf-8 />
<meta name="viewport" content="user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, minimal-ui">
<meta name="robots" content="noindex, nofollow, noimageindex, nosnippet">
<title>GraphiQL</title>
<style>
body {
Expand All @@ -22,66 +19,127 @@
}
</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 bundler.
-->
<script
src="https://unpkg.com/react@17/umd/react.development.js"
integrity="sha512-Vf2xGDzpqUOEIKO+X2rgTLWPY+65++WPwCHkX2nFMu9IcstumPsf/uKKRd5prX3wOu8Q0GBylRpsDB26R6ExOg=="
crossorigin="anonymous"
></script>
<script
src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"
integrity="sha512-Wr9OKCTtq1anK0hq5bY3X/AvDI5EflDSAh0mE9gma+4hl+kXdTJPKZ3TwLMBcrgUeoY0s3dq9JjhCQc7vddtFg=="
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/graphiql.min.css" />
<link rel="stylesheet" href="https://unpkg.com/@graphiql/plugin-explorer/dist/style.css" />
<link rel="stylesheet" href="https://unpkg.com/@graphiql/plugin-code-exporter/dist/style.css" />
</head>

<body>
<div id="graphiql">Loading...</div>
<script
src="https://unpkg.com/graphiql/graphiql.min.js"

<script src="https://unpkg.com/react@17/umd/react.development.js"
integrity="sha512-Vf2xGDzpqUOEIKO+X2rgTLWPY+65++WPwCHkX2nFMu9IcstumPsf/uKKRd5prX3wOu8Q0GBylRpsDB26R6ExOg=="
crossorigin="anonymous"></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"
integrity="sha512-Wr9OKCTtq1anK0hq5bY3X/AvDI5EflDSAh0mE9gma+4hl+kXdTJPKZ3TwLMBcrgUeoY0s3dq9JjhCQc7vddtFg=="
crossorigin="anonymous"></script>
<script src="https://unpkg.com/graphiql/graphiql.min.js"
integrity="sha512-FVCV2//UVo1qJ3Kg6kkHLe0Hg+IJhjrGa+aYHh8xD4KmwbbjthIzvaAcCJsQgA43+k+6u7HqORKXMyMt82Srfw=="
crossorigin="anonymous"
></script>
<script
src="https://unpkg.com/@graphiql/plugin-explorer@0.1.12/dist/graphiql-plugin-explorer.umd.js"
crossorigin="anonymous"></script>
<script src="https://unpkg.com/@graphiql/plugin-explorer@0.1.12/dist/graphiql-plugin-explorer.umd.js"
integrity="sha512-Fjas/uSkzvsFjbv4jqU9nt4ulU7LDjiMAXW2YFTYD96NgKS1fhhAsGR4b2k2VaVLsE29aia3vyobAq9TNzusvA=="
crossorigin="anonymous"
></script>
crossorigin="anonymous"></script>
<script src="https://unpkg.com/@graphiql/plugin-code-exporter/dist/graphiql-plugin-code-exporter.umd.js"
integrity="sha512-NwP+k36ExLYeIqp2lniZCblbz/FLJ/lQlBV55B6vafZWIYppwHUp1gCdvlaaUjV95RWPInQy4z/sIa56psJy/g=="
crossorigin="anonymous"></script>

<script>
function GraphiQLWithExplorer() {
var serverUrl = '/${graphQLEndpoint}';
var subscriptionUrl = '/${subscriptionsEndpoint}';
var fetcher = GraphiQL.createFetcher({
url: serverUrl,
subscriptionUrl
});

var fetchSnippet = {
language: 'JavaScript',
name: 'Fetch',
codeMirrorMode: 'jsx',
options: [],
generate: (generateOptions) => {
const operation = generateOptions.operationDataList[0];
const context = generateOptions.context;
const headers = context.headers.length !== 0 ? `headers: ${context.headers},\n ` : '';
const variables = JSON.stringify(operation.variables);
return `
const res = await fetch("${context.serverUrl}", {
method: 'POST',
${headers}body: JSON.stringify({
operationName: "${operation.name}",
query: \`${operation.query.replaceAll("\n", "\\n")}\`,
variables: ${variables}
}),
});

const { errors, data } = await res.json();

// Do something with the response
console.log(data, errors);
`;
}
};

var curlSnippet = {
language: 'Bash',
name: 'Curl',
codeMirrorMode: 'jsx',
options: [],
generate: (generateOptions) => {
const operation = generateOptions.operationDataList[0];
const context = generateOptions.context;
let headersObject;
try {
headersObject = JSON.parse(context.headers);
} catch (e) {
headersObject = {};
}
const headers = Object.entries(headersObject)
.reduce((acc, [headerName, headerValue]) => `${acc} -H '${headerName}: ${headerValue}' \\\n`, '');
const payload = JSON.stringify({
operationName: operation.name,
query: `${operation.query.replaceAll("\n", "\\n")}`,
variables: operation.variables
})
return `curl '${context.serverUrl}' \\\n${headers}--data-raw $'${payload}' --compressed`;
}
}

function GraphiQLWithPlugins() {
var [query, setQuery] = React.useState('');
var [variables, setVariables] = React.useState('');
var [headers, setHeaders] = React.useState('');
var defaultHeaders = `{\n "content-type": "application/json"\n}`;

var explorerPlugin = GraphiQLPluginExplorer.useExplorerPlugin({
query: query,
query,
onEdit: setQuery,
});
var exporterPlugin = GraphiQLPluginCodeExporter.useExporterPlugin({
query,
variables,
context: { serverUrl, headers },
snippets: [curlSnippet, fetchSnippet]
});

return React.createElement(GraphiQL, {
fetcher: GraphiQL.createFetcher({
url: '/${graphQLEndpoint}',
subscriptionUrl: '/${subscriptionsEndpoint}'
}),
defaultEditorToolsVisibility: true,
plugins: [explorerPlugin],
query: query,
fetcher,
query,
onEditQuery: setQuery,
variables,
onEditVariables: setVariables,
headers: '',
onEditHeaders: setHeaders,
defaultHeaders,
defaultEditorToolsVisibility: true,
plugins: [explorerPlugin, exporterPlugin]
});
}

ReactDOM.render(
React.createElement(GraphiQLWithExplorer),
document.getElementById('graphiql'),
React.createElement(GraphiQLWithPlugins),
document.getElementById('graphiql')
);
</script>
</body>

</html>