graphql_schema 1.0.4

graphql_schema #

Pub build status

An implementation of GraphQL's type system in Dart. Supports any platform where Dart runs. The decisions made in the design of this library were done to make the experience as similar to the JavaScript reference implementation as possible, and to also correctly implement the official specification.

Contains functionality to build all GraphQL types:

  • String
  • Int
  • Float
  • Boolean
  • GraphQLObjectType
  • GraphQLUnionType
  • GraphQLEnumType
  • GraphQLInputObjectType
  • Date - ISO-8601 Date string, deserializes to a Dart DateTime object

Of course, for a full description of GraphQL's type system, see the official specification: http://facebook.github.io/graphql/October2016/

Mostly analogous to graphql-js; many names are verbatim: https://graphql.org/graphql-js/type/

Usage #

It's easy to define a schema with the helper functions:

final GraphQLSchema todoSchema = new GraphQLSchema(
    query: objectType('Todo', [
  field('text', graphQLString.nonNullable()),
  field('created_at', graphQLDate)
]));

All GraphQL types are generic, in order to leverage Dart's strong typing support.

Serialization #

GraphQL types can serialize and deserialize input data. The exact implementation of this depends on the type.

var iso8601String = graphQLDate.serialize(new DateTime.now());
var date = graphQLDate.deserialize(iso8601String);
print(date.millisecondsSinceEpoch);

Validation #

GraphQL types can validate input data.

var validation = myType.validate('@root', {...});

if (validation.successful) {
  doSomething(validation.value);
} else {
  print(validation.errors);
}

Helpers #

  • graphQLSchema - Create a GraphQLSchema
  • objectType - Create a GraphQLObjectType with fields
  • field - Create a GraphQLField with a type/argument/resolver
  • listOf - Create a GraphQLListType with the provided innerType
  • inputObjectType - Creates a GraphQLInputObjectType
  • inputField - Creates a field for a GraphQLInputObjectType

Types #

All of the GraphQL scalar types are built in, as well as a Date type:

  • graphQLString
  • graphQLId
  • graphQLBoolean
  • graphQLInt
  • graphQLFloat
  • graphQLDate

Non-Nullable Types #

You can easily make a type non-nullable by calling its nonNullable method.

List Types #

Support for list types is also included. Use the listType helper for convenience.

/// A non-nullable list of non-nullable integers
listOf(graphQLInt.nonNullable()).nonNullable();

Input values and parameters #

Take the following GraphQL query:

{
   anime {
     characters(title: "Hunter x Hunter") {
        name
        age
     }
   }
}

The field characters accepts a parameter, title. To reproduce this in package:graphql_schema, use GraphQLFieldInput:

final GraphQLObjectType queryType = objectType('AnimeQuery', fields: [
  field('characters',
    listOf(characterType.nonNullable()),
    inputs: [
      new GraphQLFieldInput('title', graphQLString.nonNullable())
    ]
  ),
]);

final GraphQLObjectType characterType = objectType('Character', fields: [
  field('name', graphQLString),
  field('age', graphQLInt),
]);

In the majority of cases where you use GraphQL, you will be delegate the actual fetching of data to a database object, or some asynchronous resolver function.

package:graphql_schema includes this functionality in the resolve property, which is passed a context object and a Map<String, dynamic> of arguments.

A hypothetical example of the above might be:

var field = field(
  'characters',
  graphQLString,
  resolve: (_, args) async {
    return await myDatabase.findCharacters(args['title']);
  },
);

1.0.4 #

  • Add convert method to types, to avoid some annoying generics bugs.

1.0.3 #

  • enumTypeFromStrings now returns GraphQLEnumType<String>.

1.0.2 #

  • Added GraphQLClass().
  • Added typeName.

1.0.1 #

  • Dart 2 updates.

example/example.dart

import 'package:graphql_schema/graphql_schema.dart';

final GraphQLSchema todoSchema = new GraphQLSchema(
  queryType: objectType('Todo', fields: [
    field(
      'text',
      graphQLString.nonNullable(),
      resolve: resolveToNull,
    ),
    field(
      'created_at',
      graphQLDate,
      resolve: resolveToNull,
    ),
  ]),
);

main() {
  // Validation
  var validation = todoSchema.queryType.validate(
    '@root',
    {
      'foo': 'bar',
      'text': null,
      'created_at': 24,
    },
  );

  if (validation.successful) {
    print('This is valid data!!!');
  } else {
    print('Invalid data.');
    validation.errors.forEach((s) => print('  * $s'));
  }

  // Serialization
  print(todoSchema.queryType.serialize({
    'text': 'Clean your room!',
    'created_at': new DateTime.now().subtract(new Duration(days: 10))
  }));
}

Use this package as a library

1. Depend on it

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


dependencies:
  graphql_schema: ^1.0.4

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_schema/graphql_schema.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
39
Health:
Code health derived from static analysis. [more]
89
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
66
Learn more about scoring.

We analyzed this package on Jul 17, 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_schema/graphql_schema.dart.

Health suggestions

Fix lib/src/object_type.dart. (-4.89 points)

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

line 33 col 67: Use = to separate a named parameter from its default value.

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

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

line 123 col 9: DO use curly braces for all flow control structures.

line 134 col 9: DO use curly braces for all flow control structures.

Fix lib/src/type.dart. (-1.99 points)

Analysis of lib/src/type.dart reported 4 hints:

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

line 81 col 9: DO use curly braces for all flow control structures.

line 83 col 9: DO use curly braces for all flow control structures.

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

Fix lib/src/gen.dart. (-1.49 points)

Analysis of lib/src/gen.dart reported 3 hints:

line 6 col 21: Use = to separate a named parameter from its default value.

line 24 col 55: Use = to separate a named parameter from its default value.

line 38 col 50: Use = to separate a named parameter from its default value.

Fix additional 4 files with analysis or formatting issues. (-2.99 points)

Additional issues in the following files:

  • lib/src/scalar.dart (3 hints)
  • lib/src/argument.dart (1 hint)
  • lib/src/field.dart (1 hint)
  • lib/src/schema.dart (1 hint)

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=1.8.0 <3.0.0
collection ^1.0.0 1.14.11
meta ^1.0.0 1.1.7
source_span ^1.0.0 1.5.5
Transitive dependencies
charcode 1.1.2
path 1.6.2
term_glyph 1.1.0
Dev dependencies
test >=0.12.0 <2.0.0

Admin