graphql 4.0.0-alpha.1 copy "graphql: ^4.0.0-alpha.1" to clipboard
graphql: ^4.0.0-alpha.1 copied to clipboard

outdated

A stand-alone GraphQL client for Dart, bringing all the features from a modern GraphQL client to one easy to use package.

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: ^4.0.0-alpha

And then import it inside your dart code:

import 'package:graphql/client.dart';

Migration Guide #

Find the migration from version 3 to version 4 here.

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. 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 GraphQLCache.

// ...

final HttpLink _httpLink = HttpLink(
    '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: GraphQLCache(
          // The default store is the InMemoryStore, which does NOT persist to disk
          store: HiveStore(),
        ),
        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 document - Use our built-in help function - gql(query) to convert your document string to ASTs document.

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


const int nRepositories = 50;

final QueryOptions options = QueryOptions(
    document: 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(
  document: 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 document instead. document will be removed from the api in a future version.

For example:

// ...

final MutationOptions options = MutationOptions(
  document: 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(
  document: 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());
});

To improve performance you can make use of a concept introduced by Apollo called Automatic persisted queries (or short "APQ") to send smaller requests and even enabled CDN caching for your GraphQL API.

ATTENTION: This also requires you to have a GraphQL server that supports APQ, like Apollo's GraphQL Server and will only work for queries (but not for mutations or subscriptions).

You can than use it simply by prepending a PersistedQueriesLink to your normal HttpLink:

final PersistedQueriesLink _apqLink = PersistedQueriesLink(
  // To enable GET queries for the first load to allow for CDN caching
  useGETForHashedQueries: true,
);

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

final Link _link = _apqLink.concat(_httpLink);
463
likes
0
pub points
98%
popularity

Publisher

verified publisherzino.company

A stand-alone GraphQL client for Dart, bringing all the features from a modern GraphQL client to one easy to use package.

Homepage
Repository (GitHub)
View/report issues

License

unknown (license)

Dependencies

collection, gql, gql_dedupe_link, gql_error_link, gql_exec, gql_http_link, gql_link, gql_transform_link, gql_websocket_link, hive, http, meta, normalize, path

More

Packages that depend on graphql