Skip to content

Commit

Permalink
single interface for fetch (#172)
Browse files Browse the repository at this point in the history
* single interface for fetch (observables becomes promises when it expects only one value)
  • Loading branch information
DxCx authored and asiandrummer committed Oct 13, 2016
1 parent d6993fc commit 373404b
Showing 1 changed file with 21 additions and 2 deletions.
23 changes: 21 additions & 2 deletions src/components/GraphiQL.js
Original file line number Diff line number Diff line change
Expand Up @@ -420,7 +420,7 @@ export class GraphiQL extends React.Component {

const fetcher = this.props.fetcher;

const fetch = fetcher({ query: introspectionQuery });
const fetch = observableToPromise(fetcher({ query: introspectionQuery }));
if (!isPromise(fetch)) {
this.setState({
response: 'Fetcher did not return a Promise for introspection.'
Expand All @@ -435,7 +435,9 @@ 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.
const fetch2 = fetcher({ query: introspectionQuerySansSubscriptions });
const fetch2 = observableToPromise(fetcher({
query: introspectionQuerySansSubscriptions
}));
if (!isPromise(fetch)) {
throw new Error('Fetcher did not return a Promise for introspection.');
}
Expand Down Expand Up @@ -895,6 +897,23 @@ function isPromise(value) {
return typeof value === 'object' && typeof value.then === 'function';
}

// Duck-type Observable.take(1).toPromise()
function observableToPromise(observable) {
if ( !isObservable(observable) ) {
return observable;
}
return new Promise((resolve, reject) => {
const subscription = observable.subscribe(v => {
resolve(v);
subscription.unsubscribe();
}, e => {
reject(e);
}, () => {
reject(new Error('no value resolved'));
});
});
}

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

0 comments on commit 373404b

Please sign in to comment.