### Running GraphQL Client Example Commands Source: https://github.com/zino-hofmann/graphql-flutter/blob/main/packages/graphql/example/README.md These shell commands demonstrate how to interact with the Dart GraphQL client example application. You can list repositories, and star or unstar a specific repository using its ID. Repository IDs can be obtained by running the 'List repositories' command. ```sh # List repositories pub run example # Star Repository (you can get repository ids from `pub run example`) pub run example -a star --id $REPOSITORY_ID # Unstar Repository pub run example -a unstar --id $REPOSITORY_ID ``` -------------------------------- ### Start Star Wars Demo GraphQL Server Source: https://github.com/zino-hofmann/graphql-flutter/blob/main/examples/starwars/README.md This command builds the server components and then runs the GraphQL server in the background, making its API available for client consumption. ```bash make && make server !& ``` -------------------------------- ### Example Git Commit Message: Documentation Update Source: https://github.com/zino-hofmann/graphql-flutter/blob/main/docs/dev/MAINTAINERS.md Illustrates a concise Git commit message for documentation changes, demonstrating the 'docs' type and 'changelog' scope. ```Git docs(changelog): update changelog to beta.5 ``` -------------------------------- ### Example Git Commit Body with Stacktrace Source: https://github.com/zino-hofmann/graphql-flutter/blob/main/docs/dev/MAINTAINERS.md Demonstrates how to include detailed information, such as stack traces or error messages, within the commit body. This practice ensures that critical debugging information is indexed and easily searchable for future reference. ```Git checker: fixes overloading operation when the type is optimized The stacktrace is the following one } expected `Foo` not `Foo` - both operands must be the same type for operator overloading 11 | } 12 | 13 | fn (_ Foo) == (_ Foo) bool { | ~~~ 14 | return true 15 | } Signed-off-by: Vincenzo Palazzo ``` -------------------------------- ### Install GraphQL Client for Dart Source: https://github.com/zino-hofmann/graphql-flutter/blob/main/packages/graphql/README.md Instructions to add the `graphql` package as a dependency to a Dart/Flutter project using `flutter pub add` and import it into Dart code. ```console $ flutter pub add graphql ``` ```Dart import 'package:graphql/client.dart'; ``` -------------------------------- ### Example Git Commit Message: Bug Fix with Body Source: https://github.com/zino-hofmann/graphql-flutter/blob/main/docs/dev/MAINTAINERS.md Provides an example of a Git commit message for a bug fix, including a detailed body explaining the dependency update required. This showcases how to provide context beyond the subject line. ```Git fix(release): need to depend on latest rxjs and zone.js The version in our package.json gets copied to the one we publish, and users need the latest of these. ``` -------------------------------- ### Install GraphQL Flutter Package via Pub Source: https://github.com/zino-hofmann/graphql-flutter/blob/main/packages/graphql_flutter/README.md Adds the `graphql_flutter` package to your Flutter project's `pubspec.yaml` dependencies using the `flutter pub add` command, making it available for use. ```console $ flutter pub add graphql_flutter ``` -------------------------------- ### Project Directory Structure Overview Source: https://github.com/zino-hofmann/graphql-flutter/blob/main/packages/graphql/ARCHITECTURE.md Displays the top-level directory structure of the `graphql-flutter` project, showing the `example`, `lib`, and `test` directories with a depth limit of 3, providing an initial understanding of the project's organization. ```bash tree -L 3 -d . . ├── example │   ├── bin │   └── lib ├── lib │   └── src │   ├── cache # cache and store abstractions │   ├── core # │   ├── exceptions # client exceptions / link exception wrappers │   ├── links # custom and re-exported gql_links │   ├── scheduler # used by ObservableQuery for polling │   └── utilities # helpers like gql └── test └── cache ``` -------------------------------- ### Generate Changelogs for GraphQL Flutter Packages Source: https://github.com/zino-hofmann/graphql-flutter/blob/main/docs/dev/MAINTAINERS.md Utilize `make` commands to automate the generation of changelogs. `changelog_client` targets the `graphql` package, `changelog_flutter` targets `graphql_flutter`, and `changelog` generates for both. Ensure `GITHUB_TOKEN` is set. ```Shell make {changelog_client|changelog_flutter|changelog} ``` -------------------------------- ### Implement GraphQL Subscription with Flutter Subscription Widget Source: https://github.com/zino-hofmann/graphql-flutter/blob/main/packages/graphql_flutter/README.md This example shows how to use the `Subscription` widget in a stateful Flutter widget to listen for real-time updates from a GraphQL subscription. It includes handling loading states, exceptions, and accumulating results using the `ResultAccumulator` helper widget. ```dart final subscriptionDocument = gql( r''' subscription reviewAdded { reviewAdded { stars, commentary, episode } } ''', ); class _MyHomePageState extends State { @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Subscription( options: SubscriptionOptions( document: subscriptionDocument, ), builder: (result) { if (result.hasException) { return Text(result.exception.toString()); } if (result.isLoading) { return Center( child: const CircularProgressIndicator(), ); } // ResultAccumulator is a provided helper widget for collating subscription results. // careful though! It is stateful and will discard your results if the state is disposed return ResultAccumulator.appendUniqueEntries( latest: result.data, builder: (context, {results}) => DisplayReviews( reviews: results.reversed.toList(), ), ); } ), ) ); } } ``` -------------------------------- ### Composing GraphQL Links with Link.from and split Source: https://github.com/zino-hofmann/graphql-flutter/blob/main/packages/graphql/README.md This snippet illustrates a comprehensive setup for GraphQL links, showing how to combine common links, split terminating links based on request type (e.g., subscriptions vs. HTTP), and apply specific authentication links. It highlights the importance of `split` for multiple terminating links. ```Dart Link.from([ // common links run before every request DedupeLink(), // dedupe requests ErrorLink(onException: reportClientException), ]).split( // split terminating links, or they will break (request) => request.isSubscription, MyCustomSubscriptionAuthLink().concat( WebSocketLink(mySubscriptionEndpoint), ), // MyCustomSubscriptionAuthLink is only applied to subscriptions AuthLink(getToken: httpAuthenticator).concat( HttpLink(myAppEndpoint), ) ); ``` -------------------------------- ### Verify Java Version for Android Build Source: https://github.com/zino-hofmann/graphql-flutter/blob/main/packages/graphql_flutter/README.md Executes a shell command to display the installed Java Development Kit (JDK) version. Java 17 is a prerequisite for building Android applications with this project. ```sh java -version ``` -------------------------------- ### Set GitHub Personal Access Token Source: https://github.com/zino-hofmann/graphql-flutter/blob/main/docs/dev/MAINTAINERS.md Before executing release commands that interact with GitHub, set the `GITHUB_TOKEN` environment variable. This token must have sufficient permissions to create releases and access repository data. ```Shell export GITHUB_TOKEN="your_token" ``` -------------------------------- ### Using client.fetchMore for Data Pagination in Dart Source: https://github.com/zino-hofmann/graphql-flutter/blob/main/changelog-v3-v4.md This experimental Dart example demonstrates how to implement `client.fetchMore` to retrieve additional data, such as for pagination, when `watchQuery` is not in use. It illustrates the process of resolving `fetchMore` options based on the `latestResult` and updating the query logic. ```dart /// Untested example code class MyQuery { QueryResult latestResult; QueryOptions initialOptions; FetchMoreOptions get _fetchMoreOptions { // resolve the fetchMore params based on some data in lastestResult, // like last item id or page number, and provide custom updateQuery logic } Future fetchMore() async { final result = await client.fetchMore( _fetchMoreOptions, originalOptions: options, previousResult: latestResult, ); latestResult = result; return result; } } ``` -------------------------------- ### Execute GraphQL Query using useQuery Hook in Dart Source: https://github.com/zino-hofmann/graphql-flutter/blob/main/packages/graphql_flutter/README.md Provides an alternative method for executing GraphQL queries using the useQuery hook from the flutter_hooks package. It shows how to retrieve query results and handle different states (loading, error, data) in a more functional, hook-based style, similar to the Query widget example. ```Dart final readRespositoriesResult = useQuery( QueryOptions( document: gql(readRepositories), // this is the query string you just created variables: { 'nRepositories': 50, }, pollInterval: const Duration(seconds: 10), ), ); final result = readRespositoriesResult.result; if (result.hasException) { return Text(result.exception.toString()); } if (result.isLoading) { return const Text('Loading'); } List? repositories = result.data?['viewer']?['repositories']?['nodes']; if (repositories == null) { return const Text('No repositories'); } return ListView.builder( itemCount: repositories.length, itemBuilder: (context, index) { final repository = repositories[index]; return Text(repository['name'] ?? ''); }); ``` -------------------------------- ### Using client.watchQuery for Reactive Data Listening Source: https://github.com/zino-hofmann/graphql-flutter/blob/main/packages/graphql/README.md `client.watchQuery` allows executing GraphQL queries and mutations while reactively listening to cache changes. This example shows how to set up an `ObservableQuery` to fetch data, handle loading states, exceptions, and process results from the stream. ```Dart final observableQuery = client.watchQuery( WatchQueryOptions( fetchResults: true, document: gql( r''' query HeroForEpisode($ep: Episode!) { hero(episode: $ep) { name } } ''', ), variables: {'ep': 'NEWHOPE'}, ), ); /// Listen to the stream of results. This will include: /// * `options.optimisitcResult` if passed /// * The result from the server (if `options.fetchPolicy` includes networking) /// * rebroadcast results from edits to the cache observableQuery.stream.listen((QueryResult result) { if (!result.isLoading && result.data != null) { if (result.hasException) { print(result.exception); return; } if (result.isLoading) { print('loading'); return; } doSomethingWithMyQueryResult(myCustomParser(result.data)); } }); // ... cleanup: observableQuery.close(); ``` -------------------------------- ### Define GraphQL Schema with Interfaces and Unions for Normalization Source: https://github.com/zino-hofmann/graphql-flutter/blob/main/packages/graphql/README.md Presents a GraphQL schema example featuring an interface (`PersonI`), concrete types (`Employee`, `InStoreCustomer`, `OnlineCustomer`), and a union (`CustomerU`). This schema is used to illustrate the need for a `possibleTypes` map for correct fragment resolution and cache normalization. ```GraphQL interface PersonI { name: String age: Int } type Employee implements PersonI { name: String age: Int daysOfEmployement: Int } type InStoreCustomer implements PersonI { name: String age: Int numberOfPurchases: Int } type OnlineCustomer implements PersonI { name: String age: Int numberOfPurchases: Int } union CustomerU = OnlineCustomer | InStoreCustomer ``` -------------------------------- ### Trigger GraphQL Pagination with fetchMore() Call Source: https://github.com/zino-hofmann/graphql-flutter/blob/main/packages/graphql_flutter/README.md This example shows how to trigger the `fetchMore()` function, typically from a UI element like a `RaisedButton`, by passing the pre-configured `FetchMoreOptions` to initiate a new GraphQL operation and fetch additional data for pagination. ```Dart RaisedButton( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text("Load More"), ], ), onPressed: () { fetchMore(opts); }, ) ``` -------------------------------- ### Define GraphQL Query String in Dart Source: https://github.com/zino-hofmann/graphql-flutter/blob/main/packages/graphql_flutter/README.md Shows how to define a multi-line GraphQL query string in Dart. This example defines a 'ReadRepositories' query that accepts an integer variable for the number of repositories to fetch, retrieving their ID, name, and star status. ```Dart String readRepositories = """ query ReadRepositories(\$nRepositories: Int!) { viewer { repositories(last: \$nRepositories) { nodes { id name viewerHasStarred } } } } """; ``` -------------------------------- ### Advanced GraphQL Mutation with Cache Update and Optimistic Result Source: https://github.com/zino-hofmann/graphql-flutter/blob/main/packages/graphql_flutter/README.md This comprehensive example illustrates a `Mutation` widget in Flutter, configuring `MutationOptions` for a GraphQL operation. It details the `update` callback for manual cache manipulation using `cache.writeFragment` to update specific fragments, handles exceptions, and demonstrates passing a pre-calculated `expectedResult` as `optimisticResult` to `toggleStar` for immediate UI feedback. ```Dart // final Map repository; // final bool optimistic; // Map extractRepositoryData(Map data); // Map get expectedResult; Mutation( options: MutationOptions( document: gql(starred ? mutations.removeStar : mutations.addStar), update: (cache, result) { if (result.hasException) { print(result.exception); } else { final updated = { ...repository, ...extractRepositoryData(result.data), }; cache.writeFragment( Fragment( document: gql( ''' fragment fields on Repository { id name viewerHasStarred } ''', // helper for constructing FragmentRequest )).asRequest(idFields: { '__typename': updated['__typename'], 'id': updated['id'], }), data: updated, broadcast: false, ); } }, onError: (OperationException error) { }, onCompleted: (dynamic resultData) { }, ), builder: (RunMutation toggleStar, QueryResult result) { return ListTile( leading: starred ? const Icon( Icons.star, color: Colors.amber, ) : const Icon(Icons.star_border), trailing: result.isLoading || optimistic ? const CircularProgressIndicator() : null, title: Text(repository['name'] as String), onTap: () { toggleStar( {'starrableId': repository['id']}, optimisticResult: expectedResult, ); }, ); }, ) ``` -------------------------------- ### Implement Server-Side WebSocket Authentication Check (TypeScript) Source: https://github.com/zino-hofmann/graphql-flutter/blob/main/packages/graphql/README.md Provides a TypeScript example of a server-side `onConnect` handler for `graphql-ws` that validates an authorization token from connection parameters and closes the socket with a custom error code if the token is invalid. ```typescript subscriptions: { 'graphql-ws': { onConnect: async (context: any) => { const { connectionParams } = context; if (!connectionParams) { throw new Error('Connection params are missing'); } const authToken = connectionParams.authorization; if (authToken) { const isValid await authService.isTokenValid(authToken); if (!isValid) { context.extra.socket.close(4001, 'Unauthorized'); } return; } }, }, }, ``` -------------------------------- ### Handle OperationException in GraphQL Flutter Source: https://github.com/zino-hofmann/graphql-flutter/blob/main/packages/graphql/README.md Illustrates how to check for and handle `OperationException` from a `QueryResult` in Dart. The example demonstrates checking `result.hasException` and then specifically identifying a `NetworkException` within `result.exception.linkException` to implement custom error handling logic. ```Dart if (result.hasException) { if (result.exception.linkException is NetworkException) { // handle network issues, maybe } return Text(result.exception.toString()) } ``` -------------------------------- ### Configure Default Policies for GraphQLClient in Dart Source: https://github.com/zino-hofmann/graphql-flutter/blob/main/packages/graphql/README.md Illustrates how to set default policies for the `GraphQLClient` itself using `DefaultPolicies`. This example specifically configures `watchMutation` behavior, allowing watched mutations to behave similarly to watched queries by defining their `FetchPolicy`, `ErrorPolicy`, and `CacheRereadPolicy`. ```Dart GraphQLClient( defaultPolicies: DefaultPolicies( // make watched mutations behave like watched queries. watchMutation: Policies( FetchPolicy.cacheAndNetwork, ErrorPolicy.none, CacheRereadPolicy.mergeOptimistic, ), ), // ... ) ``` -------------------------------- ### Standard Git Commit Message Format Source: https://github.com/zino-hofmann/graphql-flutter/blob/main/docs/dev/MAINTAINERS.md Defines the required structure for Git commit messages in the graphql-flutter project, including mandatory header components (type, scope, subject) and optional body and footer sections. Emphasizes a 100-character line limit for readability and the use of the footer for issue references. ```Git ():