zino-hofmann / graphql-flutter

A GraphQL client for Flutter, bringing all the features from a modern GraphQL client to one easy to use package.
https://zino-hofmann.github.io/graphql-flutter
MIT License
3.25k stars 623 forks source link

graphql query request without Query() widget #1260

Closed Mohdx closed 1 year ago

Mohdx commented 2 years ago

Hello y'all good moring. is there's prober way of making graphql query request without Query widget? I need to store some list to use it later in different places

it's seems much easier to do with MutationOptions() with onCompleted: && onError: as QueryOptions() doesn't have any. So I end up using .then((result){}

here's my code

class GraphQL {
  static final AuthLink _authLink = AuthLink(
    getToken: () async => 'Bearer ${Global.appSettings.token}',
  );

  static GraphQLClient client({Store? store}) {
    return GraphQLClient(
      link: _authLink.concat(HttpLink(Configs.apiUrl)),
      cache: GraphQLCache(store: store ?? InMemoryStore()),
    );
  }
}
  static String familyMembers() {
    return '''
    query familyMembers {
      familyMembers {
        id
        name
        relation
        status
        token
      }
      familyMembersRequests {
        id
        name
        mobile
        relation
        status
      }
    }
      ''';
  }

also .then((QueryResult<Object?> result) { returns null if familyMembers has data but familyMembersRequests has error

import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import 'package:provider/provider.dart';

import '/app/views/main_pages/family/provider/family_provider.dart';
import '/graphql/graphql.dart';
import '/helper/helper.dart';
import '/models/entities/family_member_model.dart';
import 'explorer/queries.dart';

class GetFamilyMembersAPI {
  GetFamilyMembersAPI(this.context);

  final BuildContext context;

  Future<void> request() async {
    GraphQL.client()
        .query(QueryOptions(document: gql(Queries.familyMembers())))
        .then((result) {
      try {
        if (result.data != null) _result(result);
      } catch (e) {
        //
      }
      return result;
    });
  }

  void _result(QueryResult<Object?> result) {
    _resultModel(result, 'familyMembers'); // get familyMembers
    _resultModel(result, 'familyMembersRequests'); // get familyMembersRequests
  }

  void _resultModel(QueryResult<Object?> result, String json) {
    if (result.data!.isNotEmpty && result.data!.containsKey(json)) {
      if (result.data![json] is List && result.data![json].isNotEmpty) {
        List<FamilyMemberModel> members = List<FamilyMemberModel>.from(
          result.data![json].map((x) {
            return FamilyMemberModel.fromJson(x);
          }),
        );

        json == 'familyMembersRequests'
            ? context.read<FamilyProvider>().getMembersRequests(members)
            : context.read<FamilyProvider>().getMembers(members);
      }
    }
  }

  // Not sure where to handel query error like MutationOptions() "onError:"
  void _error(OperationException? error) async {
    final AppLocalizations? arb = AppLocalizations.of(context);

    if (error != null && error.graphqlErrors.isNotEmpty) {
      switch (error.graphqlErrors.first.extensions?['code']) {
        case 422:
          Helper.bannerWarning('User not found');
          break;

        default:
          Helper.toast(
              '${arb!.somethingWentWrong} [${error.graphqlErrors.first.extensions?['code']}]');
      }
    }
  }
}