knaeckeKami / gql_phoenix_link

A gql Link for communicating over Phoenix Channels
MIT License
11 stars 9 forks source link

Example usage #1

Open tukruic opened 3 years ago

tukruic commented 3 years ago

For people looking for full working example call initGraphQLChannel() from initstate

void initGraphQLChannel() async {
    // your absinthe plug api location
    final HttpLink phoenixHttpLink = HttpLink(
      'http://192.168.1.23:4000/api',
    );

    // your websocket location
    String websocketUri = "ws://192.168.1.23:4000/socket/websocket";

    // creation of phoenixChannel for use in PhoenixLink
    final phoenixChannel =
        await PhoenixLink.createChannel(websocketUri: websocketUri);

    // creation of PhoenixLink
    final phoenixLink = PhoenixLink(
      channel: phoenixChannel,
    );

    // Split like in flutter graphql documentation between websocket and http requests
    var _link = Link.split(
        (request) => request.isSubscription, phoenixLink, phoenixHttpLink);
    final GraphQLClient client = GraphQLClient(
      link: _link,
      cache: GraphQLCache(),
    );

    // your subscription query
    final subscriptionDocument = gql(
      r'''
    subscription{
  postAdded{
    id
    name
    description
  }
}
  ''',
    );

    // subscribe and listen
    Stream<QueryResult> subscription = client.subscribe(
      SubscriptionOptions(document: subscriptionDocument),
    );
    subscription.listen(reactToPostCreated);
  }

  void reactToPostCreated(QueryResult event) {
    print("Received event =>");
    print(event);
  }

  // example event received structure
  // Received event =>
  // I/flutter (15033): QueryResult(source: QueryResultSource.network, data: {postAdded: {__typename: Post, id: 32, name: graphqllink post, description: something something}}, context: Context({ResponseExtensions: Instance of 'ResponseExtensions'}), exception: null, timestamp: 2021-09-02 20:15:40.365330)
knaeckeKami commented 3 years ago

Thanks! I'll add that as example code