Skip to content
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

[RFC] Support a fetcher that returns Observable #104

Merged
merged 1 commit into from
Mar 9, 2016
Merged
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ and children.
**Props:**

- `fetcher`: a function which accepts GraphQL-HTTP parameters and returns
a Promise which resolves to the GraphQL parsed JSON response.
a Promise or Observable which resolves to the GraphQL parsed JSON response.

- `schema`: a GraphQLSchema instance or `null` if one is not to be used.
If `undefined` is provided, GraphiQL will send an introspection query
Expand Down
8 changes: 6 additions & 2 deletions src/components/ExecuteButton.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ import React, { PropTypes } from 'react';
*/
export class ExecuteButton extends React.Component {
static propTypes = {
onClick: PropTypes.func
onClick: PropTypes.func,
isRunning: PropTypes.bool
}

render() {
Expand All @@ -26,7 +27,10 @@ export class ExecuteButton extends React.Component {
onClick={this.props.onClick}
title="Execute Query (Ctrl-Enter)">
<svg width="34" height="34">
<path d="M 11 9 L 24 16 L 11 23 z" />
{ this.props.isRunning ?
<path d="M 10 10 L 23 10 L 23 23 L 10 23 z" /> :
<path d="M 11 9 L 24 16 L 11 23 z" />
}
</svg>
</button>
);
Expand Down
96 changes: 82 additions & 14 deletions src/components/GraphiQL.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ import {
* Props:
*
* - fetcher: a function which accepts GraphQL-HTTP parameters and returns
* a Promise which resolves to the GraphQL parsed JSON response.
* a Promise or Observable which resolves to the GraphQL parsed
* JSON response.
*
* - schema: a GraphQLSchema instance or `null` if one is not to be used.
* If `undefined` is provided, GraphiQL will send an introspection query
Expand Down Expand Up @@ -192,6 +193,7 @@ export class GraphiQL extends React.Component {
docsOpen: false,
docsWidth: this._storageGet('docExplorerWidth') || 350,
isWaitingForResponse: false,
subscription: null,
};

// Ensure only the last executed editor query is rendered.
Expand Down Expand Up @@ -242,7 +244,13 @@ export class GraphiQL extends React.Component {

// Try the stock introspection query first, falling back on the
// sans-subscriptions query for services which do not yet support it.
fetcher({ query: introspectionQuery })
const fetch = fetcher({ query: introspectionQuery });
if (!isPromise(fetch)) {
console.error('Fetcher did not return a Promise for introspection.');
return;
}

fetch
.catch(() => fetcher({ query: introspectionQuerySansSubscriptions }))
.then(result => {
// If a schema was provided while this fetch was underway, then
Expand Down Expand Up @@ -315,7 +323,10 @@ export class GraphiQL extends React.Component {
<div className="topBarWrap">
<div className="topBar">
{logo}
<ExecuteButton onClick={this._runEditorQuery} />
<ExecuteButton
isRunning={Boolean(this.state.subscription)}
onClick={this._runOrStopEditorQuery}
/>
<GraphiQL.ToolbarButton
onClick={this._prettifyQuery}
title="Prettify Query"
Expand Down Expand Up @@ -395,36 +406,83 @@ export class GraphiQL extends React.Component {
}

_fetchQuery(query, variables, cb) {
this.props.fetcher({ query, variables }).then(cb).catch(error => {
const fetcher = this.props.fetcher;
const fetch = fetcher({ query, variables });

if (isPromise(fetch)) {
// If fetcher returned a Promise, then call the callback when the promise
// resolves, otherwise handle the error.
fetch.then(cb).catch(error => {
this.setState({
isWaitingForResponse: false,
response: error && (error.stack || String(error))
});
});
} else if (isObservable(fetch)) {
// If the fetcher returned an Observable, then subscribe to it, calling
// the callback on each next value, and handling both errors and the
// completion of the Observable. Returns a Subscription object.
const subscription = fetch.subscribe({
next: cb,
error: error => {
this.setState({
isWaitingForResponse: false,
response: error && (error.stack || String(error)),
subscription: null
});
},
complete: () => {
this.setState({
isWaitingForResponse: false,
subscription: null
});
}
});

return subscription;
} else {
this.setState({
isWaitingForResponse: false,
response: error && (error.stack || String(error))
response: 'Fetcher did not return Promise or Observable.'
});
});
}
}

_runEditorQuery = () => {
this.setState({
isWaitingForResponse: true,
response: null,
});
_runOrStopEditorQuery = () => {
// If there is a current subscription, unsubscribe from it.
if (this.state.subscription) {
this.setState({
isWaitingForResponse: false,
subscription: null
});
this.state.subscription.unsubscribe();
return;
}

this._editorQueryID++;
var queryID = this._editorQueryID;
const queryID = this._editorQueryID;

// Use the edited query after autoCompleteLeafs() runs or,
// in case autoCompletion fails (the function returns undefined),
// the current query from the editor.
let editedQuery = this.autoCompleteLeafs() || this.state.query;
const editedQuery = this.autoCompleteLeafs() || this.state.query;
const variables = this.state.variables;

this._fetchQuery(editedQuery, this.state.variables, result => {
// _fetchQuery may return a subscription.
const subscription = this._fetchQuery(editedQuery, variables, result => {
if (queryID === this._editorQueryID) {
this.setState({
isWaitingForResponse: false,
response: JSON.stringify(result, null, 2),
});
}
});

this.setState({
isWaitingForResponse: true,
response: null,
subscription
});
}

_prettifyQuery = () => {
Expand Down Expand Up @@ -699,3 +757,13 @@ function getVariableToType(schema, query) {
}
}
}

// Duck-type promise detection.
function isPromise(value) {
return typeof value === 'object' && typeof value.then === 'function';
}

// Duck-type observable detection.
function isObservable(value) {
return typeof value === 'object' && typeof value.subscribe === 'function';
}