GraphQL (vania_graphql)
The vania_graphql package integrates a GraphQL server into your Vania application with HTTP and WebSocket transport, subscriptions, and GraphiQL IDE.
Installation
dependencies:
vania_graphql: ^1.0.0
Setup
Define Your Schema
import 'package:vania_graphql/vania_graphql.dart';
final userType = objectType('User', fields: [
field('id', graphQLInt.nonNullable()),
field('name', graphQLString.nonNullable()),
field('email', graphQLString.nonNullable()),
field('posts', listOf(postType)),
]);
final postType = objectType('Post', fields: [
field('id', graphQLInt.nonNullable()),
field('title', graphQLString.nonNullable()),
field('body', graphQLString.nonNullable()),
]);
final queryType = objectType('Query', fields: [
vaniaField<Map<String, dynamic>>(
'users',
listOf(userType),
resolve: (_, context) async {
return await User().query.get();
},
),
vaniaField<Map<String, dynamic>>(
'user',
userType,
inputs: [GraphQLFieldInput('id', graphQLInt.nonNullable())],
resolve: (_, context) async {
final id = context.args['id'];
return await User().query.find(id);
},
),
]);
final mutationType = objectType('Mutation', fields: [
vaniaField<Map<String, dynamic>>(
'createUser',
userType,
inputs: [
GraphQLFieldInput('name', graphQLString.nonNullable()),
GraphQLFieldInput('email', graphQLString.nonNullable()),
],
resolve: (_, context) async {
return await User().query.create({
'name': context.args['name'],
'email': context.args['email'],
});
},
),
]);
final schema = GraphQLSchema(
queryType: queryType,
mutationType: mutationType,
);
Register the Provider
'providers': [
RouteServiceProvider(),
DatabaseServiceProvider(),
GraphQLServiceProvider(schema: schema),
],
Or register manually:
VaniaGraphQL.schema(schema);
VaniaGraphQL.routes();
Configuration
GraphQLServiceProvider(
schema: schema,
config: GraphQLConfig(
endpoint: '/graphql',
graphiqlEnabled: true,
introspectionEnabled: true,
allowGet: true,
allowPost: true,
allowSubscriptions: true,
maxQueryLength: 10000,
executionTimeout: Duration(seconds: 30),
),
);
Using GraphQL
Once configured, your GraphQL endpoint is available at /graphql.
Query
query {
users {
id
name
email
}
}
query {
user(id: 1) {
name
email
posts {
title
}
}
}
Mutation
mutation {
createUser(name: "Alice", email: "[email protected]") {
id
name
}
}