graphql 3.0.0

  • Readme
  • Changelog
  • Example
  • Installing
  • 97

MIT License All Contributors PRs Welcome

Star on GitHub Watch on GitHub Discord

Build Status Coverage version

GraphQL Client #

Installation #

First, depend on this package:

dependencies:
  graphql: ^2.0.0

And then import it inside your dart code:

import 'package:graphql/client.dart';

Parsing at build-time #

To parse documents at build-time use ast_builder from package:gql_code_gen:

dev_dependencies:
  gql_code_gen: ^0.1.0

Usage #

To connect to a GraphQL Server, we first need to create a GraphQLClient. A GraphQLClient requires both a cache and a link to be initialized.

In our example below, we will be using the Github Public API. In our example below, we are going to use HttpLink which we will concatenate with AuthLink so as to attach our github access token. For the cache, we are going to use InMemoryCache.

// ...

final HttpLink _httpLink = HttpLink(
    uri: 'https://api.github.com/graphql',
);

final AuthLink _authLink = AuthLink(
    getToken: () async => 'Bearer $YOUR_PERSONAL_ACCESS_TOKEN',
);

final Link _link = _authLink.concat(_httpLink);

final GraphQLClient _client = GraphQLClient(
        cache: InMemoryCache(),
        link: _link,
    );

// ...

Using Concat

final Link _link = _authLink.concat(_httpLink);

Using Links.from

Link.from joins multiple links into a single link at once.

final Link _link = Link.from([_authLink, _httpLink]);

Once you have initialized a client, you can run queries and mutations.

Query #

Creating a query is as simple as creating a multiline string:

const String readRepositories = r'''
  query ReadRepositories($nRepositories: Int!) {
    viewer {
      repositories(last: $nRepositories) {
        nodes {
          __typename
          id
          name
          viewerHasStarred
        }
      }
    }
  }
''';

Then create a QueryOptions object:

NB: for documentNode - Use our built-in help function - gql(query) to convert your document string to ASTs documentNode.

In our case, we need to pass nRepositories variable and the document name is readRepositories.


const int nRepositories = 50;

final QueryOptions options = QueryOptions(
    documentNode: gql(readRepositories),
    variables: <String, dynamic>{
        'nRepositories': nRepositories,
    },
);

And finally you can send the query to the server and await the response:

// ...

final QueryResult result = await _client.query(options);

if (result.hasException) {
    print(result.exception.toString());
}

final List<dynamic> repositories =
    result.data['viewer']['repositories']['nodes'] as List<dynamic>;

// ...

Mutations #

Creating a Mutation is also similar to creating a query, with a small difference. First, start with a multiline string:

const String addStar = r'''
  mutation AddStar($starrableId: ID!) {
    action: addStar(input: {starrableId: $starrableId}) {
      starrable {
        viewerHasStarred
      }
    }
  }
''';

Then instead of the QueryOptions, for mutations we will MutationOptions, which is where we pass our mutation and id of the repository we are starring.

// ...

final MutationOptions options = MutationOptions(
  documentNode: gql(addStar),
  variables: <String, dynamic>{
    'starrableId': repositoryID,
  },
);

// ...

And finally you can send the query to the server and await the response:

// ...

final QueryResult result = await _client.mutate(options);

if (result.hasException) {
    print(result.exception.toString());
    return
}

final bool isStarred =
    result.data['action']['starrable']['viewerHasStarred'] as bool;

if (isStarred) {
  print('Thanks for your star!');
  return;
}

// ...

AST documents #

We are deprecating document and recommend you update your application to use documentNode instead. document will be removed from the api in a future version.

For example:

// ...

final MutationOptions options = MutationOptions(
  documentNode: gql(addStar),
  variables: <String, dynamic>{
    'starrableId': repositoryID,
  },
);

// ...

With package:gql_code_gen you can parse your *.graphql files at build-time.

add_star.graphql:

mutation AddStar($starrableId: ID!) {
  action: addStar(input: {starrableId: $starrableId}) {
    starrable {
      viewerHasStarred
    }
  }
}
import 'package:gql/add_star.ast.g.dart' as add_star;

// ...

final MutationOptions options = MutationOptions(
  documentNode: add_star.document,
  variables: <String, dynamic>{
    'starrableId': repositoryID,
  },
);

// ...

Perform custom logic when a GraphQL or network error happens, such as logging or signing out.

final ErrorLink errorLink = ErrorLink(errorHandler: (ErrorResponse response) {
  Operation operation = response.operation;
  FetchResult result = response.fetchResult;
  OperationException exception = response.exception;
  print(exception.toString());
});

3.0.0 (2020-01-13) #

Bug Fixes #

  • cache: add value == and hashCode to lazy cache map, fix traversal (617dde7)
  • cache: AppLifecycleState.{suspending -> detached} (8bc7b14)
  • ci: attempt to fix ci (4fac2e4)
  • client: default toEncodable (5f938e4)
  • client: export operation and fetch results (5dcbae5)
  • client: make fetchMore valid with default original document again (faa3779)
  • client: organize exports alphabetically (a322339)
  • client: patch fetchMore to write to cache (9cb7474)
  • client: use http 0.12.0+4 to fix a wrong content-type header on multipart request on http 0.12.0+3 (ea8822c), closes #525
  • client: use noCache for fetchMore, avoiding normalization (da20541)
  • docs: remove moved onComplete (31a0d2f)
  • switch test to AST from document string (894dc53)
  • docs: use ast for examples (d68616e)
  • add eager result to stream, rebuild query widget on var change (af89b19)
  • bump gql dependency (b55a891)
  • don't set default policies on options so defaults are applied (fd95e37)
  • exception test cases (001cb48)
  • fix issues so example runs on latest stable (87d8feb)
  • ignore *.iml and .idea (361fdff)
  • ignore linting errors from the core (0612d44)
  • ignore uri doesn't exist lint error (e14349d)
  • individually suppress "deprecated_member_use_from_same_package" only (3879f18)
  • individually suppress "deprecated_member_use_from_same_package" only (9216976)
  • pass queryId directly instead of ObservableQuery object (405ae24)
  • remove analysis_options.yaml as its ineffective (0a8d05d)
  • remove equatable package (0c32b14)
  • remove equitable package and update tests (dbe4db5)
  • subscriptions reconnect (fd8f3d1)
  • subscriptions reconnect (c310db2)
  • suppress fix: individually suppress "deprecated_member_use_from_same_package" only (511630f)
  • temporary disable assertion which is failing (3cf7333)
  • update .gitignore with standard flutter paths (892fe36)
  • graphql-flutter: replace document string with AST Document (23e40af)
  • update starwars example (8aaa99b)
  • example: depend on updated angel server, add paging example (609c4ec)
  • flutter: prevent observable discarding in MutationState.didChangeDependencies (baeca25)
  • flutter: return callback results in case of futures to await (c7d6fd1)
  • graphql-flutter: ignore ast errors in the core (3b16f3f)
  • packaging: update rxdart and sdk min versions (1980f22), closes #497
  • tests: clobbered tests from library-level exceptions (f76e165)
  • tests: fix failing tests seemingly to to ast-switch (664fdd1)
  • use AST for graphql client example (edf7df6)
  • use case else instead of detached or suspended (9fb5aab)

Features #

  • client: add error link (de9714a), closes #419 #440
  • client: cache.reset() added (8c4f2e2)
  • client: introduce Policies class for options and add defaults to client (fa24aab)
  • client: library-level exception handling (20e57bd)
  • client: library-level exceptions (8976cfc)
  • client: support defining operations from document AST (fa2db11)
  • client: support joining multiple links at once (9565244)
  • attempt to call mutation callbacks from mutation method (e323a4d)
  • better message on UnhandledFailure (eccab11)
  • document exception handling (b38e2a3)
  • flutter: add mutation callback for onError (1ff0b8f)
  • graphql-client: re-export parseString as gql (dcd5508)
  • update examples to gql instead of parse string (7b9ac57)
  • updating example (1a1bc43)
  • use equatable package to make it easier to compare links (a7ed072)

BREAKING CHANGES #

  • packaging: projects dependent on old sdk/rxdart versions wouldn't build, there is a way to override rxdart dependency with dependency_override (we don't use Observable features in these places, so it should be compatible with older version) there is no way to override min sdk version outside of a project
  • client: replaces result.errors with result.exception

3.0.0-beta.3 (2020-01-09) #

Bug Fixes #

  • client: use http 0.12.0+4 to fix a wrong content-type header on multipart request on http 0.12.0+3 (ea8822c), closes #525

3.0.0-beta.2 (2020-01-08) #

Bug Fixes #

  • packaging: update rxdart and sdk min versions (1980f22), closes #497

BREAKING CHANGES #

  • packaging: projects dependent on old sdk/rxdart versions wouldn't build, there is a way to override rxdart dependency with dependency_override (we don't use Observable features in these places, so it should be compatible with older version) there is no way to override min sdk version outside of a project

3.0.0-beta.1 (2019-12-22) #

Bug Fixes #

  • cache: add value == and hashCode to lazy cache map, fix traversal (617dde7)
  • cache: AppLifecycleState.{suspending -> detached} (8bc7b14)
  • ci: attempt to fix ci (4fac2e4)
  • client: default toEncodable (5f938e4)
  • client: export operation and fetch results (5dcbae5)
  • client: make fetchMore valid with default original document again (faa3779)
  • client: organize exports alphabetically (a322339)
  • client: patch fetchMore to write to cache (9cb7474)
  • client: use noCache for fetchMore, avoiding normalization (da20541)
  • docs: remove moved onComplete (31a0d2f)
  • docs: use ast for examples (d68616e)
  • example: depend on updated angel server, add paging example (609c4ec)
  • flutter: prevent observable discarding in MutationState.didChangeDependencies (baeca25)
  • flutter: return callback results in case of futures to await (c7d6fd1)
  • pass queryId directly instead of ObservableQuery object (405ae24)
  • graphql-flutter: ignore ast errors in the core (3b16f3f)
  • add eager result to stream, rebuild query widget on var change (af89b19)
  • bump gql dependency (b55a891)
  • don't set default policies on options so defaults are applied (fd95e37)
  • exception test cases (001cb48)
  • fix issues so example runs on latest stable (87d8feb)
  • ignore *.iml and .idea (361fdff)
  • ignore linting errors from the core (0612d44)
  • ignore uri doesn't exist lint error (e14349d)
  • individually suppress "deprecated_member_use_from_same_package" only (3879f18)
  • individually suppress "deprecated_member_use_from_same_package" only (9216976)
  • remove analysis_options.yaml as its ineffective (0a8d05d)
  • remove equatable package (0c32b14)
  • remove equitable package and update tests (dbe4db5)
  • subscriptions reconnect (c310db2)
  • subscriptions reconnect (fd8f3d1)
  • suppress fix: individually suppress "deprecated_member_use_from_same_package" only (511630f)
  • switch test to AST from document string (894dc53)
  • temporary disable assertion which is failing (3cf7333)
  • update .gitignore with standard flutter paths (892fe36)
  • update starwars example (8aaa99b)
  • use AST for graphql client example (edf7df6)
  • graphql-flutter: replace document string with AST Document (23e40af)
  • tests: clobbered tests from library-level exceptions (f76e165)
  • tests: fix failing tests seemingly to to ast-switch (664fdd1)
  • use case else instead of detached or suspended (9fb5aab)

Features #

  • client: add error link (de9714a), closes #419 #440
  • client: cache.reset() added (8c4f2e2)
  • client: introduce Policies class for options and add defaults to client (fa24aab)
  • client: library-level exception handling (20e57bd)
  • client: library-level exceptions (8976cfc)
  • client: support defining operations from document AST (fa2db11)
  • client: support joining multiple links at once (9565244)
  • attempt to call mutation callbacks from mutation method (e323a4d)
  • better message on UnhandledFailure (eccab11)
  • document exception handling (b38e2a3)
  • flutter: add mutation callback for onError (1ff0b8f)
  • graphql-client: re-export parseString as gql (dcd5508)
  • update examples to gql instead of parse string (7b9ac57)
  • updating example (1a1bc43)
  • use equatable package to make it easier to compare links (a7ed072)

BREAKING CHANGES #

  • client: replaces result.errors with result.exception

See GitHub Releases.

  • Loosened initPayload to dynamic to support many use-cases, Removed InitOperation's excessive and inconsistent json encoding. Old implmentation can still be utilized as legacyInitPayload until deprecation

  • Fixed broken anonymous operations

example/README.md

Example Dart Application #

This is a simple command line application to showcase how you can use the Dart GraphQL Client, without flutter.

To run this application:

  1. First clone this repository and navigate to this directory

  2. Install all dart dependencies

  3. create a file bin/local.dart with the content:

    const String YOUR_PERSONAL_ACCESS_TOKEN =
       '<YOUR_PERSONAL_ACCESS_TOKEN>';
    
  4. Then run the Application using the commands below:

    1. List Your Repositories
    pub run main.dart
    
    1. Star Repository
    pub run main.dart -a star --id <REPOSITORY_ID_HERE>
    
    1. Unstar Repository
    pub run main.dart -a unstar --id <REPOSITORY_ID_HERE>
    

NB: Replace repository id in the last two commands with a real Github Repository ID. You can get by running the first command, IDs are printed on the console.

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  graphql: ^3.0.0

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter pub get

Alternatively, your editor might support pub get or flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:graphql/client.dart';
import 'package:graphql/internal.dart';
import 'package:graphql/legacy_socket_api/legacy_socket_client.dart';
import 'package:graphql/legacy_socket_api/legacy_socket_link.dart';
import 'package:graphql/utilities.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
95
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
97
Learn more about scoring.

We analyzed this package on Mar 27, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.7.1
  • pana: 0.13.6

Health suggestions

Format lib/legacy_socket_api/legacy_socket_client.dart.

Run dartfmt to format lib/legacy_socket_api/legacy_socket_client.dart.

Format lib/src/socket_client.dart.

Run dartfmt to format lib/src/socket_client.dart.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.6.0 <3.0.0
gql ^0.12.0 0.12.2
http ^0.12.0+4 0.12.0+4
http_parser ^3.1.3 3.1.4
meta ^1.1.6 1.1.8
mime ^0.9.6+2 0.9.6+3
path ^1.6.2 1.6.4
quiver >=2.0.0 <3.0.0 2.1.3
rxdart ^0.23.1 0.23.1 0.24.0-dev.1
uuid_enhanced ^3.0.2 3.0.2
websocket ^0.0.5 0.0.5
Transitive dependencies
async 2.4.1
charcode 1.1.3
collection 1.14.12
convert 2.1.1
crypto 2.1.4
matcher 0.12.6
source_span 1.7.0
stack_trace 1.9.3
string_scanner 1.0.5
term_glyph 1.1.0
typed_data 1.1.6
Dev dependencies
mockito ^4.0.0
pedantic ^1.8.0+1 1.9.0
test ^1.5.3
test_coverage ^0.3.0+1