Last active
May 15, 2020 16:43
-
-
Save ampersanda/fe2e37f52faa1a31184fb0f2c326c29b to your computer and use it in GitHub Desktop.
Base Abstraction for GraphQL request
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/widgets.dart'; | |
import 'package:gql/language.dart'; | |
import 'package:graphql_flutter/graphql_flutter.dart'; | |
import 'package:provider/provider.dart'; | |
enum BaseServiceRequestType { QUERY, MUTATION } | |
/// [T] is a return value | |
abstract class BaseService<T> { | |
/// [context] is a navigator context, this context doesn't have | |
/// capability to grab [MediaQuery] or [OverlayState] | |
/// This context have to be a final member and has an [owner] | |
BuildContext get context => Catcher.navigatorKey.currentContext; | |
GQLClient get _gqlClient { | |
final GQLClient client = Provider.of<GQLClient>(context, listen: false); | |
return client; | |
} | |
FetchPolicy get fetchPolicy => FetchPolicy.networkOnly; | |
T onPostExecute(QueryResult result) { | |
if (result.hasException) { | |
throw Exception(result.exception.graphqlErrors.first.message); | |
} | |
return null; | |
} | |
Future<QueryResult> _call() { | |
final GraphQLClient client = _gqlClient.client; | |
if (serviceType == BaseServiceRequestType.QUERY) { | |
final MutationOptions options = MutationOptions( | |
documentNode: parseString(query), | |
variables: parameter, | |
fetchPolicy: fetchPolicy, | |
); | |
return client.mutate(options); | |
} else if (serviceType == BaseServiceRequestType.MUTATION) { | |
final QueryOptions options = QueryOptions( | |
documentNode: parseString(query), | |
variables: parameter, | |
fetchPolicy: fetchPolicy, | |
); | |
return client.query(options); | |
} | |
return null; | |
} | |
Future<T> fetch<T>() async { | |
final QueryResult result = await _call(); | |
return onPostExecute(result) as T; | |
} | |
String get query; | |
BaseServiceRequestType get serviceType; | |
Map<String, dynamic> get parameter; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment