[graphiql] Support pasting in GraphQL request format (JSON) and in "Copy as cURL" format
- Dominant language
- TypeScript
- Stars
- 16.9k
- Forks
- 1.9k
- Avg merge
- 22h 45m
- Merged PRs (30d)
- 70
Description
I'm checking graphql requests of my frontend via Developer Tools > Network tab, where I can either copy the Request text from Preview tab, which is a JSON, or I can right-click on the request and select "Copy as cURL", which will copy the shell command syntax with headers and `--data-binary` followed by JSON of GraphQL request again.
It would be nice to automatically analyse the text from paste buffer, when user paste it in GraphiQL and set *query*, *variables* and *headers* accordingly.
I've made a dirty hack on my copy of `graphiql.html`, which can be used as a starting point of that UX.
```html
GraphiQL
body {
height: 100%;
margin: 0;
width: 100%;
overflow: hidden;
}
#graphiql {
height: 100vh;
}
var fetcher = GraphiQL.createFetcher({
url: "https://swapi-graphql.netlify.app/.netlify/functions/index",
});
const readDataBinary = true;
const readHeaders = true;
/**
* These headers will be overridden by browser anyway
*/
const skipHeaders = [
"Content-Type",
"Origin",
"Cookie",
"Content-Length",
//"Accept-Language",
"Host",
"User-Agent",
"Referer",
"Accept-Encoding",
"Connection",
].map((x) => x.toLowerCase());
var zSetQuery = {};
var zSetVariables = {};
var zSetHeaders = {};
function smartSetJSON(data) {
const obj = JSON.parse(data);
if ("query" in obj) {
zSetQuery(obj["query"]);
}
if ("variables" in obj) {
zSetVariables(JSON.stringify(obj["variables"]));
}
}
function handlepaste(x, event) {
const data = event.clipboardData.getData("Text");
try {
smartSetJSON(data);
} catch (e) {
console.debug("Not a JSON, checking for cURL format");
if (readDataBinary) {
const regex = /\s+--data-binary\s'(.*)'/g;
const matches = [...data.matchAll(regex)];
for (i in matches) {
smartSetJSON(matches[i][1]);
}
}
if (readHeaders) {
const regex = /\s+-H\s'([^:]+):\s+(.*)'/g;
const matches = [...data.matchAll(regex)];
const headers = {};
for (i in matches) {
if (!skipHeaders.includes(matches[i][1].toLowerCase())) {
headers[matches[i][1]] = matches[i][2];
}
}
if (headers !== {}) {
zSetHeaders(JSON.stringify(headers));
}
}
}
}
function CustomGraphiQL() {
var [query, setQuery] = React.useState(``);
var [variables, setVariables] = React.useState(``);
var [headers, setHeaders] = React.useState(``);
zSetQuery = setQuery;
zSetVariables = setVariables;
zSetHeaders = setHeaders;
return React.createElement(GraphiQL, {
fetcher: fetcher,
defaultEditorToolsVisibility: true,
plugins: [],
query: query,
onEditQuery: setQuery,
variables: variables,
onEditVariables: setVariables,
headers: headers,
onEditHeaders: setHeaders,
});
}
ReactDOM.render(
React.createElement(CustomGraphiQL),
document.getElementById("graphiql")
);
```
Contributor guide
Assessment
This issue has not been assessed yet.