query method
GQL Query using the Dart Http package
url
is your gql endpoint.
query is your String query.
variables
is the map of variables if your query need variables.
headers
if you want to tweaks the request's headers.
Example
import 'package:simple_gql/simple_gql.dart';
final response = await GQLClient(
url: 'https://your_gql_endpoint',
).query(
query: r'''
query PostsForAuthor($id: Int!) {
author(id: $id) {
firstName
posts {
title
votes
}
}
}
''',
variables: { 'id': 1 }
);
Implementation
Future<GQLResponse> query(
{required String query,
Map<String, dynamic>? variables,
Map<String, String>? headers}) async {
try {
return await post(Uri.parse(endpoint),
headers: (headers ?? _headers)
..putIfAbsent('content-type', () => 'application/json'),
body: jsonEncode({'query': query, 'variables': variables}))
.then((res) {
final body = jsonDecode(res.body);
if ((body['errors'] as List?)?.isNotEmpty ?? false) {
throw GQLError._getErrors(body['errors']).first;
}
return GQLResponse(data: body['data'], httpResponse: res);
});
} catch (e) {
rethrow;
}
}