createSupporterRequest method Null safety

Future<SupporterRequest?> createSupporterRequest()

Creates a new supporter request token. Returns null if the request failed. Returns a SupporterRequest entity on success. A user logged in as a supporter can use the token contained in that entity to establish a link with the patient who originally created the token.

Implementation

Future<SupporterRequest?> createSupporterRequest() async {
  const gqlQueryString = '''
      mutation CreateSupporterRequest {
        createSupporterRequest(
          input: {
            data: {
              patient: "12345"
              token: "replaceme"
            }
          }
        ) {
          supporterRequest {
            ${SupporterRequestGqlEntity.gqlQueryFragment}
          }
        }
      }
    ''';

  try {
    final queryResult = await graphQLClient
        .mutate<void>(MutationOptions(document: gql(gqlQueryString)));

    if (queryResult.hasException) {
      logger?.e(queryResult.exception.toString());
      return null;
    }

    final requestData = queryResult.data!['createSupporterRequest']
        ['supporterRequest'] as Map<String, dynamic>;

    if (requestData.isNotEmpty) {
      final requestGqlEntity =
          SupporterRequestGqlEntity.fromJson(requestData);

      if (requestGqlEntity != null) {
        return requestGqlEntity.toSupporterRequest();
      }
    }

    return null;
  } catch (e, stackTrace) {
    logger?.e('Could not create supporter request token', e, stackTrace);
    return null;
  }
}