Flexible, lightweight transport layer for GraphQL
npm install apollo-linkapollo-link is a standard interface for modifying control flow of GraphQL requests and fetching GraphQL results, designed to provide a simple GraphQL client that is capable of extensions.
apollo-link are highlighted below:
next(result) on the observer. In the case of a network/transport error (not a GraphQL Error) the error(err) method can be used to indicate a response will not be recieved. If multiple responses are not supported by the link, complete() should be called to inform the client no further data will be provided.
request(operation, forward) is the link to forward(operation) to. forward returns an observable and it can be returned directly or subscribed to.
js
forward(operation).subscribe({
next: result => {
handleTheResult(result)
},
error: error => {
handleTheNetworkError(error)
},
});
`
Implementing a basic custom transport
`js
import { ApolloLink, Observable } from 'apollo-link';
export class CustomApolloLink extends ApolloLink {
request(operation /, forward/) {
//Whether no one is listening anymore
let unsubscribed = false;
return new Observable(observer => {
somehowGetOperationToServer(operation, (error, result) => {
if (unsubscribed) return;
if (error) {
//Network error
observer.error(error);
} else {
observer.next(result);
observer.complete(); //If subscriptions not supported
}
});
function unsubscribe() {
unsubscribed = true;
}
return unsubscribe;
});
}
}
`
Installation
npm install apollo-link --save`