graphql 2.1.0

  • Readme
  • Changelog
  • Example
  • Installing
  • 94

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';

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 concatinate 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,
    );

...

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 with the query string as the document and pass any variables necessary.

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


const int nRepositories = 50;

final QueryOptions options = QueryOptions(
    document: 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.hasErrors) {
    print(result.errors);
}

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

...

Mutations #

Creating a Matation 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: 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.hasErrors) {
  print(result.errors);
  return;
}

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

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

...

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: ^2.1.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]
92
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
90
Overall:
Weighted score of the above. [more]
94
Learn more about scoring.

We analyzed this package on Dec 7, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.6.1
  • pana: 0.12.21

Platforms

Detected platforms: Flutter, other

Platform components identified in package: io.

Health suggestions

Format lib/src/cache/in_memory_html.dart.

Run dartfmt to format lib/src/cache/in_memory_html.dart.

Format lib/src/cache/in_memory_io.dart.

Run dartfmt to format lib/src/cache/in_memory_io.dart.

Format lib/src/cache/in_memory_stub.dart.

Run dartfmt to format lib/src/cache/in_memory_stub.dart.

Fix additional 6 files with analysis or formatting issues.

Additional issues in the following files:

  • lib/src/core/graphql_error.dart (Run dartfmt to format lib/src/core/graphql_error.dart.)
  • lib/src/link/http/link_http_helper_deprecated_io.dart (Run dartfmt to format lib/src/link/http/link_http_helper_deprecated_io.dart.)
  • lib/src/link/http/link_http_helper_deprecated_stub.dart (Run dartfmt to format lib/src/link/http/link_http_helper_deprecated_stub.dart.)
  • lib/src/utilities/file_html.dart (Run dartfmt to format lib/src/utilities/file_html.dart.)
  • lib/src/utilities/file_stub.dart (Run dartfmt to format lib/src/utilities/file_stub.dart.)
  • lib/src/utilities/traverse.dart (Run dartfmt to format lib/src/utilities/traverse.dart.)

Maintenance issues and suggestions

Support latest dependencies. (-10 points)

The version constraint in pubspec.yaml does not support the latest published versions for 1 dependency (rxdart).

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.2.2 <3.0.0
graphql_parser ^1.1.3 1.1.4
http ^0.12.0+2 0.12.0+2
http_parser ^3.1.3 3.1.3
meta ^1.1.6 1.1.8
mime ^0.9.6+2 0.9.6+3
path ^1.6.2 1.6.4
rxdart ^0.22.0 0.22.6 0.23.0-dev.2
uuid_enhanced ^3.0.2 3.0.2
websocket ^0.0.5 0.0.5
Transitive dependencies
async 2.4.0
charcode 1.1.2
collection 1.14.12
convert 2.1.1
crypto 2.1.4
source_span 1.5.5
string_scanner 1.0.5
term_glyph 1.1.0
typed_data 1.1.6
Dev dependencies
mockito ^4.0.0
pedantic <=1.7.99 1.9.0
test ^1.5.3
test_coverage ^0.2.0