graphql_server 2.0.0-beta

graphql_server #

Pub build status

Base package for implementing GraphQL servers. You might prefer package:angel_graphql, the fastest way to implement GraphQL backends in Dart.

package:graphql_server does not require any specific framework, and thus can be used in any Dart project.

Ad-hoc Usage #

The actual querying functionality is handled by the GraphQL class, which takes a schema (from package:graphql_schema). In most cases, you'll want to call parseAndExecute on some string of GraphQL text. It returns either a Stream or Map<String, dynamic>, and can potentially throw a GraphQLException (which is JSON-serializable):

try {
    var data = await graphQL.parseExecute(responseText);

    if (data is Stream) {
        // Handle a subscription somehow...
    } else {
        response.send({'data': data});
} on GraphQLException catch(e) {

Consult the API reference for more:

If you're looking for functionality like graphQLHttp in graphql-js, that is not included in this package, because it is typically specific to the framework/platform you are using. The graphQLHttp implementation in package:angel_graphql is a good example:

Subscriptions #

GraphQL queries involving subscription operations can return a Stream. Ultimately, the transport for relaying subscription events to clients is not specified in the GraphQL spec, so it's up to you.

Note that in a schema like this:

type TodoSubscription {
    onTodo: TodoAdded!

type TodoAdded {
    id: ID!
    text: String!
    isComplete: Bool

Your Dart schema's resolver for onTodo should be a Map containing an onTodo key:

  resolve: (_, __) {
    return someStreamOfTodos()
            .map((todo) => {'onTodo': todo});

For the purposes of reusing existing tooling (i.e. JS clients, etc.), package:graphql_server rolls with an implementation of Apollo's subscriptions-transport-ws spec.

NOTE: At this point, Apollo's spec is extremely out-of-sync with the protocol their client actually expects. See the following issue to track this:

The implementation is built on package:stream_channel, and therefore can be used on any two-way transport, whether it is WebSockets, TCP sockets, Isolates, or otherwise.

Users of this package are expected to extend the Server abstract class. Server will handle the transport and communication, but again, ultimately, emitting subscription events is up to your implementation.

Here's a snippet from graphQLWS in package:angel_graphql. It runs within the context of one single request:

var channel = IOWebSocketChannel(socket);
var client = stw.RemoteClient(channel.cast<String>());
var server =
    _GraphQLWSServer(client, graphQL, req, res, keepAliveInterval);
await server.done;

See graphQLWS in package:angel_graphql for a good example:

Introspection #

Introspection of a GraphQL schema allows clients to query the schema itself, and get information about the response the server expects. The GraphQL class handles this automatically, so you don't have to write any code for it.

However, you can call the reflectSchema method to manually reflect a schema:

Mirrors Usage #

By default, dart:mirrors is not required, but it can be optionally used.

The mirrorsFieldResolver can resolve fields from concrete objects, instead of you first having to serialize them:

You can also use convertDartType to convert a concrete Dart type into a GraphQLType. However, the ideal choice is package:graphql_generator.

2.0.0-beta #

  • Migrate away from package:graphql_parser, and instead use package:gql/language.dart.

1.1.0 #

  • Updates for package:graphql_parser@1.2.0.
  • Now that variables are InputValueContext descendants, handle them the same way as other values in coerceArgumentValues. TLDR - Removed now-obsolete, variable-specific logic in coerceArgumentValues.
  • Pass argumentName, not fieldName, to type validations.

1.0.3 #

  • Make field resolution asynchronous.
  • Make introspection cycle-safe.
  • Thanks @deep-guarav and @micimize!

1.0.2 #

1.0.1 #

  • Fix a bug where globalVariables were not being properly passed to field resolvers.

1.0.0 #

  • Finish testing.
  • Add package:pedantic fixes.

1.0.0-rc.0 #

  • Get the Apollo support working with the latest version of subscriptions-transport-ws.

1.0.0-beta.4 #

For some reason, Pub was not including subscriptions_transport_ws.dart.

1.0.0-beta.3 #

  • Introspection on subscription types (if any).

1.0.0-beta.2 #

  • Fix bug where field aliases would not be resolved.

1.0.0-beta.1 #

  • Add (currently untested) subscription support.

1.0.0-beta #

  • First release.


import 'package:graphql_schema/graphql_schema.dart';
import 'package:graphql_server/graphql_server.dart';
import 'package:test/test.dart';

void main() {
  test('single element', () async {
    var todoType = objectType('todo', fields: [
        resolve: (obj, args) => obj.text,
        resolve: (obj, args) => obj.completed,

    var schema = graphQLSchema(
      queryType: objectType('api', fields: [
          resolve: (_, __) => [
              text: 'Clean your room!',
              completed: false,

    var graphql = GraphQL(schema);
    var result = await graphql.parseAndExecute('{ todos { text } }');

    expect(result, {
      'todos': [
        {'text': 'Clean your room!'}

class Todo {
  final String text;
  final bool completed;

  Todo({this.text, this.completed});

Use this package as a library

1. Depend on it

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

  graphql_server: ^2.0.0-beta

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_server/graphql_server.dart';
Describes how popular the package is relative to other packages. [more]
Code health derived from static analysis. [more]
Reflects how tidy and up-to-date the package is. [more]
Weighted score of the above. [more]
Learn more about scoring.

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

  • Dart: 2.7.1
  • pana: 0.13.5

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 (recase).

Package is pre-release. (-5 points)

Pre-release versions should be used with caution; their API can change in breaking ways.


Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0 <3.0.0
angel_serialize ^2.0.0 2.2.3+3
collection ^1.0.0 1.14.12
gql ^0.12.0 0.12.0
graphql_schema ^1.0.0 1.0.4
meta ^1.0.0 1.1.8
recase ^2.0.0 2.0.1 3.0.0
stream_channel ^2.0.0 2.0.0
tuple ^1.0.0 1.0.3
Transitive dependencies
angel_model 1.0.3
async 2.4.0
charcode 1.1.2
matcher 0.12.6
path 1.6.4
quiver 2.1.2+1
quiver_hashcode 2.0.0
source_span 1.6.0
stack_trace 1.9.3
term_glyph 1.1.0
Dev dependencies
pedantic ^1.0.0 1.9.0
test >=0.12.0 <2.0.0