|
| 1 | +--- |
| 2 | +id: subscriptions |
| 3 | +title: Subscriptions |
| 4 | +--- |
| 5 | + |
| 6 | +Executing a GraphQL Subscription with Ferry is similar to queries, but with a few key differences: |
| 7 | + |
| 8 | +1. Setting up a WebSocket link for subscriptions |
| 9 | +2. Listening to the returned Stream for real-time updates |
| 10 | + |
| 11 | + |
| 12 | +## Setting up WebSocket Link |
| 13 | + |
| 14 | +First, you need to set up a WebSocket link for subscriptions. You can use the `gql_websocket_link` package for this. To add it to your project, run: |
| 15 | +(if using apollo use the TransportWebSocketLink) |
| 16 | + |
| 17 | +```yaml |
| 18 | +dependencies: |
| 19 | + gql_websocket_link: |
| 20 | +``` |
| 21 | +
|
| 22 | +create the link: |
| 23 | +
|
| 24 | +```dart |
| 25 | +Link.split( |
| 26 | + (request) => |
| 27 | + request.operation.getOperationType() == OperationType.subscription, |
| 28 | + TransportWebSocketLink( |
| 29 | + TransportWsClientOptions( |
| 30 | + socketMaker: WebSocketMaker.url(() => 'ws://<your url>/graphql'), |
| 31 | + connectionParams: () => |
| 32 | + // add your auth headers here |
| 33 | + webSocketHeaders), |
| 34 | + ), |
| 35 | + DioLink('https://<your url>/graphql', client: dio, defaultHeaders: headers), |
| 36 | + ) |
| 37 | +``` |
| 38 | + |
| 39 | + |
| 40 | +## Creating the GraphQL Subscription Request |
| 41 | + |
| 42 | +Let's say we have a `NewReviews` Subscription saved in a file named `new_reviews.graphql`: |
| 43 | + |
| 44 | +```graphql |
| 45 | +subscription NewReviews { |
| 46 | + newReviews { |
| 47 | + id |
| 48 | + title |
| 49 | + content |
| 50 | + author { |
| 51 | + id |
| 52 | + name |
| 53 | + } |
| 54 | + } |
| 55 | +} |
| 56 | +``` |
| 57 | + |
| 58 | +after the file is created run your codegen command. |
| 59 | + |
| 60 | +## Using the Subscription |
| 61 | + |
| 62 | +Now that we have our subscription set up, we can use it in our Dart code. Here's an example of how to use the `NewReviews` subscription: |
| 63 | + |
| 64 | +```dart |
| 65 | +Stream<NewReviews?> getNewReviews() { |
| 66 | + final request = GNewReviewsReq(); |
| 67 | +
|
| 68 | + try { |
| 69 | + final resultStream = _ferryService.request<GNewReviewsData, GNewReviewsVars>(request); |
| 70 | + return resultStream.asyncMap((response) { |
| 71 | + final data = response.data?.newReviews; |
| 72 | + if (data != null) { |
| 73 | + return NewReviews( |
| 74 | + id: data.id, |
| 75 | + title: data.title, |
| 76 | + content: data.content, |
| 77 | + author: data.author, |
| 78 | + ); |
| 79 | + } |
| 80 | + return null; |
| 81 | + }); |
| 82 | + } catch (e) { |
| 83 | + print('Failed to get new reviews: $e'); |
| 84 | + rethrow; |
| 85 | + } |
| 86 | +} |
| 87 | +``` |
| 88 | + |
| 89 | + |
0 commit comments