graphql_schema2 8.0.0
graphql_schema2: ^8.0.0 copied to clipboard
An implementation of GraphQL's type system in Dart. Basis of graphql_server2.
GraphQL Schema 2 #
An implementation of GraphQL's type system in Dart. It runs on any platform Dart runs on, and does not use dart:mirrors. It is designed to be close to the JavaScript reference implementation, graphql-js, and many names are the same.
It builds every GraphQL type:
- the scalars
String,Int,Float,BooleanandID, andDate, an ISO 8601 string that deserializes to a DartDateTime; - object types and interfaces (
GraphQLObjectType); - input object types (
GraphQLInputObjectType); - enum types (
GraphQLEnumType); - union types (
GraphQLUnionType); - list and non-null types.
For the full description of GraphQL's type system, see the GraphQL specification.
To execute queries against a schema, use package:graphql_server2. To generate types from Dart classes, use package:graphql_generator2.
Installation #
dependencies:
graphql_schema2: ^8.0.0
Usage #
Define a schema with the helper functions:
import 'package:graphql_schema2/graphql_schema2.dart';
final todoType = objectType(
'Todo',
fields: [
field('text', graphQLString.nonNullable()),
field('created_at', graphQLDate),
],
);
final todoSchema = graphQLSchema(
queryType: objectType(
'Query',
fields: [
field(
'todos',
listOf(todoType.nonNullable()),
resolve: (_, _) => [
{'text': 'Clean your room!', 'created_at': DateTime.now()},
],
),
],
),
);
All GraphQL types are generic, GraphQLType<Value, Serialized>: Value is the Dart value, and Serialized its form in a request or response.
Helpers #
graphQLSchemacreates aGraphQLSchema.objectTypecreates aGraphQLObjectTypewith fields, and withisInterface: truean interface.fieldcreates a field of an object type, with its type, arguments (inputs) andresolvecallback.listOfcreates a list of another type.inputObjectTypeandinputFieldcreate an input object type and its fields.enumTypeandenumTypeFromStringscreate an enum type.
The scalar types are graphQLString, graphQLId, graphQLBoolean, graphQLInt, graphQLFloat and graphQLDate.
Non-null and list types #
Call nonNullable() on a type to make it non-null, and use listOf for lists:
/// [Int!]!: a non-null list of non-null integers.
final scores = listOf(graphQLInt.nonNullable()).nonNullable();
A list item may be null only if the item type is nullable, and the Dart list type can hold null: listOf(graphQLString) is a list of non-nullable Dart Strings, while listOf<dynamic, dynamic>(graphQLString) accepts null items.
Arguments and resolvers #
Take this query:
{
characters(title: "Hunter x Hunter") {
name
age
}
}
and its schema:
type Query {
characters(title: String!): [Character!]
}
type Character {
name: String
age: Int
}
Give a field its arguments with GraphQLFieldInput, and a resolve callback that loads its value. The callback gets the parent value, the object the field belongs to, and a map of the arguments:
final characterType = objectType(
'Character',
fields: [field('name', graphQLString), field('age', graphQLInt)],
);
final queryType = objectType(
'Query',
fields: [
field(
'characters',
listOf(characterType.nonNullable()),
inputs: [GraphQLFieldInput('title', graphQLString.nonNullable())],
resolve: (_, args) async => findCharacters(args['title'] as String),
),
],
);
Future<List<Map<String, dynamic>>> findCharacters(String title) async => [
{'name': 'Gon', 'age': 12},
];
A field without a resolve callback is read from its parent by name when the parent is a Map. To resolve fields of other objects, such as model classes, give the fields resolvers, or generate them with package:graphql_generator2:
class Character {
final String name;
Character(this.name);
}
final characterNameType = objectType(
'CharacterName',
fields: [
field(
'name',
graphQLString,
resolve: (character, _) => (character as Character).name,
),
],
);
Enums #
enumType maps the names of an enum to Dart values, and enumTypeFromStrings to strings of the same names:
enum Color { red, green }
final colorType = enumType('Color', {'RED': Color.red, 'GREEN': Color.green});
final sizeType = enumTypeFromStrings('Size', ['SMALL', 'LARGE']);
A resolver can return the Dart value, such as Color.red, which is output as its name, RED. A Dart enum value named like one of the type's names, such as a Size.SMALL, is output as that name too, so a model serialized to a map, which keeps its enum values, can be returned.
Input objects #
Arguments of object shape use input object types:
final todoInput = inputObjectType(
'TodoInput',
inputFields: [
inputField('text', graphQLString.nonNullable()),
inputField('done', graphQLBoolean),
],
);
coerceToInputObject() builds the input type of an object type, named ${name}Input. It is built once, and shared by every field that refers to the object type, so a type that refers to itself works. A field whose type cannot be an input is left out if it is nullable, such as a union or an interface; a non-null one, an interface itself, or an object with no input fields left, throws an UnsupportedError.
Custom scalars #
Extend GraphQLScalarType for a scalar of your own. validate checks input and returns a ValidationResult.ok of its value or a ValidationResult.failure of its errors; serialize and deserialize convert between the Dart value and its form in requests and responses:
/// A URL, as a string in requests and responses.
class GraphQLUrlType extends GraphQLScalarType<Uri, String> {
@override
String get name => 'Url';
@override
String get description => 'An absolute URL.';
@override
ValidationResult<String> validate(String key, input) {
if (input is String && (Uri.tryParse(input)?.isAbsolute ?? false)) {
return ValidationResult.ok(input);
}
return ValidationResult.failure(['Expected "$key" to be an absolute URL.']);
}
@override
Uri deserialize(String serialized) => Uri.parse(serialized);
@override
String serialize(Uri value) => value.toString();
@override
GraphQLType<Uri, String> coerceToInputObject() => this;
}
Use it as any other type, for fields and arguments. A scalar used by the schema can be the type of a variable, as $url: Url, and introspection lists it.
Serialization and validation #
A type can serialize a Dart value, deserialize it back, and validate input:
void main() {
var iso8601String = graphQLDate.serialize(DateTime.now());
var date = graphQLDate.deserialize(iso8601String);
print(date.millisecondsSinceEpoch);
var validation = todoType.validate('@root', {'text': 'Clean your room!'});
if (validation.successful) {
print(validation.value);
} else {
print(validation.errors);
}
}
validate returns a failed ValidationResult for input of the wrong type, rather than throwing. An Int is accepted, and converted, where a Float is expected.
See the change log for what changed in 8.0.0.