graphql_server 1.0.0

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) {
    response.send(e.toJson());
}

Consult the API reference for more: https://pub.dartlang.org/documentation/graphql_server/latest/graphql_server/GraphQL/parseAndExecute.html

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: https://github.com/angel-dart/graphql/blob/master/angel_graphql/lib/src/graphql_http.dart

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:

field(
  'onTodo',
  todoAddedType,
  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: https://github.com/apollographql/subscriptions-transport-ws/issues/551

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: https://github.com/angel-dart/graphql/blob/master/angel_graphql/lib/src/graphql_ws.dart

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: https://pub.dartlang.org/documentation/graphql_server/latest/introspection/reflectSchema.html

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: https://pub.dartlang.org/documentation/graphql_server/latest/graphql_server.mirrors/mirrorsFieldResolver.html

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

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.

example/main.dart

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: [
      field(
        'text',
        graphQLString,
        resolve: (obj, args) => obj.text,
      ),
      field(
        'completed',
        graphQLBoolean,
        resolve: (obj, args) => obj.completed,
      ),
    ]);

    var schema = graphQLSchema(
      queryType: objectType('api', fields: [
        field(
          'todos',
          listOf(todoType),
          resolve: (_, __) => [
                new Todo(
                  text: 'Clean your room!',
                  completed: false,
                )
              ],
        ),
      ]),
    );

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

    print(result);
    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:


dependencies:
  graphql_server: ^1.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_server/graphql_server.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
17
Health:
Code health derived from static analysis. [more]
83
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
54
Learn more about scoring.

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

  • Dart: 2.4.0
  • pana: 0.12.19

Platforms

Detected platforms: Flutter, web, other

No platform restriction found in primary library package:graphql_server/graphql_server.dart.

Health suggestions

Fix lib/graphql_server.dart. (-5.84 points)

Analysis of lib/graphql_server.dart reported 12 hints, including:

line 49 col 7: DO use curly braces for all flow control structures.

line 51 col 7: DO use curly braces for all flow control structures.

line 119 col 7: DO use curly braces for all flow control structures.

line 245 col 7: DO use curly braces for all flow control structures.

line 250 col 7: DO use curly braces for all flow control structures.

Fix lib/src/apollo/server.dart. (-4.89 points)

Analysis of lib/src/apollo/server.dart reported 10 hints, including:

line 22 col 17: DO use curly braces for all flow control structures.

line 24 col 17: DO use curly braces for all flow control structures.

line 43 col 17: DO use curly braces for all flow control structures.

line 45 col 17: DO use curly braces for all flow control structures.

line 50 col 17: DO use curly braces for all flow control structures.

Fix lib/introspection.dart. (-4.41 points)

Analysis of lib/introspection.dart reported 9 hints, including:

line 112 col 13: DO use curly braces for all flow control structures.

line 217 col 11: DO use curly braces for all flow control structures.

line 219 col 11: DO use curly braces for all flow control structures.

line 221 col 11: DO use curly braces for all flow control structures.

line 223 col 11: DO use curly braces for all flow control structures.

Fix lib/src/apollo/transport.dart. (-1.99 points)

Analysis of lib/src/apollo/transport.dart reported 4 hints:

line 48 col 7: DO use curly braces for all flow control structures.

line 50 col 7: DO use curly braces for all flow control structures.

line 52 col 7: DO use curly braces for all flow control structures.

line 54 col 7: DO use curly braces for all flow control structures.

Fix lib/mirrors.dart. (-1 points)

Analysis of lib/mirrors.dart reported 2 hints:

line 11 col 5: DO use curly braces for all flow control structures.

line 13 col 5: DO use curly braces for all flow control structures.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=1.8.0 <3.0.0
angel_serialize ^2.0.0 2.2.3+2
collection ^1.0.0 1.14.11
graphql_parser ^1.0.0 1.1.3
graphql_schema ^1.0.0 1.0.4
meta ^1.0.0 1.1.7
recase ^2.0.0 2.0.1
stream_channel ^2.0.0 2.0.0
tuple ^1.0.0 1.0.2
Transitive dependencies
angel_model 1.0.3
async 2.2.0
charcode 1.1.2
matcher 0.12.5
path 1.6.2
quiver 2.0.3
quiver_hashcode 2.0.0
source_span 1.5.5
stack_trace 1.9.3
string_scanner 1.0.4
term_glyph 1.1.0
Dev dependencies
pedantic ^1.0.0
test >=0.12.0 <2.0.0

Admin