UNPKG

2.37 kBMarkdownView Raw
1# apollo-link
2
3## Purpose
4
5`apollo-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.
6The targeted use cases of `apollo-link` are highlighted below:
7
8* fetch queries directly without normalized cache
9* network interface for Apollo Client
10* network interface for Relay Modern
11* fetcher for
12
13Apollo Link is the interface for creating new links in your application.
14
15The client sends a request as a method call to a link and can recieve one or more (in the case of subscriptions) responses from the server. The responses are returned using the Observer pattern.
16
17![Apollo Link Chain](https://cdn-images-1.medium.com/max/1600/1*62VLGUaU-9ULCoBCGvgdkQ.png)
18
19Results from the server can be provided by calling `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.
20
21In the case of an intermediate link, a second argument to `request(operation, forward)` is the link to `forward(operation)` to. `forward` returns an observable and it can be returned directly or subscribed to.
22
23```js
24forward(operation).subscribe({
25 next: result => {
26 handleTheResult(result)
27 },
28 error: error => {
29 handleTheNetworkError(error)
30 },
31});
32```
33
34## Implementing a basic custom transport
35
36```js
37import { ApolloLink, Observable } from 'apollo-link';
38
39export class CustomApolloLink extends ApolloLink {
40 request(operation /*, forward*/) {
41 //Whether no one is listening anymore
42 let unsubscribed = false;
43
44 return new Observable(observer => {
45 somehowGetOperationToServer(operation, (error, result) => {
46 if (unsubscribed) return;
47 if (error) {
48 //Network error
49 observer.error(error);
50 } else {
51 observer.next(result);
52 observer.complete(); //If subscriptions not supported
53 }
54 });
55
56 function unsubscribe() {
57 unsubscribed = true;
58 }
59
60 return unsubscribe;
61 });
62 }
63}
64```
65
66## Installation
67
68`npm install apollo-link --save`
69