-
-
Notifications
You must be signed in to change notification settings - Fork 9.1k
/
preview.js
35 lines (31 loc) · 1007 Bytes
/
preview.js
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
import React from 'react';
import GraphiQL from 'graphiql';
import FullScreen from './components/FullScreen';
import 'graphiql/graphiql.css';
const FETCH_OPTIONS = {
method: 'post',
headers: { 'Content-Type': 'application/json' },
};
function getDefautlFetcher(url) {
return function(params) {
const body = JSON.stringify(params);
const options = Object.assign({ body }, FETCH_OPTIONS);
return fetch(url, options).then(res => res.json());
};
}
function reIndentQuery(query) {
const lines = query.split('\n');
const spaces = lines[lines.length - 1].length - 1;
return lines.map((l, i) => (i === 0 ? l : l.slice(spaces)).join('\n'));
}
export function setupGraphiQL(config) {
return function(_query, variables = '{}') {
const query = reIndentQuery(_query);
const fetcher = config.fetcher || getDefautlFetcher(config.url);
return () => (
<FullScreen>
<GraphiQL query={query} variables={variables} fetcher={fetcher} />
</FullScreen>
);
};
}