findRequestByToken method Null safety

Future<SupporterRequest?> findRequestByToken(
  1. String token
)

Finds a supporter request that's linked to a given token. Returns null if no request exists for this token or returns a valid instance of SupporterRequest in case the request exists. Use the request instance with resolveSupporterRequest to trade the token for a patient-supporter link. This method is only successful if executed by a patient.

Implementation

Future<SupporterRequest?> findRequestByToken(String token) async {
  final gqlQueryString = '''
    query FetchSupporterRequest {
      supporterRequests(
        where: {
          token: "$token"
        }
      ) {
        ${SupporterRequestGqlEntity.gqlQueryFragment}
      }
    }
  ''';

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

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

    final data = queryResult.data!['supporterRequests'] as List<dynamic>;

    if (data.isNotEmpty) {
      final supporterRequestData = data.first as Map<String, dynamic>;
      final gqlSupporterRequest =
          SupporterRequestGqlEntity.fromJson(supporterRequestData);

      return gqlSupporterRequest?.toSupporterRequest();
    }

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