Created
November 8, 2019 03:20
-
-
Save acao/73430b31bca4b3f2fa87b37a77563874 to your computer and use it in GitHub Desktop.
renderGraphiQL Helper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
import { GraphiQL } from './components/GraphiQL'; | |
const logger = console; | |
const defaultOptions = { | |
containerId: 'root', | |
url: 'http://localhost:8080', | |
}; | |
const getFetcher = async opts => { | |
// only load isomorphic fetch if a fetcher is not provided | |
const { default: fetch } = await import('isomorphic-fetch'); | |
if (!opts.containerEl || opts.containerId) { | |
logger.warn('no containerEl or containerId provided, defaulting to #root'); | |
} | |
if (!opts.url || !opts.fetcher) { | |
logger.warn( | |
'no url or custom fetcher provided, defaulting to POSTs against http://localhost:8080', | |
); | |
} | |
const resultFn = async graphQLParams => { | |
const result = await fetch(opts.url, { | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/json', | |
...opts.headers, | |
}, | |
body: JSON.stringify(graphQLParams), | |
}); | |
return result.json(); | |
}; | |
return resultFn; | |
}; | |
export default async function renderGraphiQL(options = {}) { | |
const opts = { ...defaultOptions, ...options }; | |
if (!opts.fetcher) { | |
opts.fetcher = await getFetcher(opts); | |
} | |
return ReactDOM.render( | |
<GraphiQL {...opts} />, | |
opts.containerEl || document.getElementById(opts.containerId), | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment