graphQLPost function

Future<GraphqlResponse> graphQLPost({
  1. required Uri uri,
  2. required String query,
  3. IMap<String, JsonValue>? variables,
  4. String? auth,
})

Implementation

Future<GraphqlResponse> graphQLPost({
  required Uri uri,
  required String query,
  IMap<String, JsonValue>? variables,
  String? auth,
}) async {
  final http.Response response = await http.post(
    uri,
    body: JsonObject(
      IMap({
        'query': JsonString(query),
        'variables':
            variables == null ? const JsonNull() : JsonObject(variables),
      }),
    ).encode(),
    headers: {
      'content-type': 'application/json',
      if (auth != null) 'authorization': 'Bearer $auth',
    },
  );
  final jsonValue = JsonValue.decode(
    utf8.decode(response.bodyBytes),
  );

  final errors = jsonValue
          .getObjectValueOrNull('errors')
          ?.getAsArrayWithDecoder((errorJson) {
        final message =
            errorJson.getObjectValueOrNull('message')?.asStringOrNull();
        final path = IList(errorJson
            .getObjectValueOrNull('path')
            ?.getAsArray()
            ?.map((element) {
          switch (element.asStringOrNull()) {
            case final v?:
              return PathItemString(v);
          }
          switch (element.asDoubleOrNull()) {
            case final v?:
              return PathItemInt(v.toInt());
          }
          throw Exception('expected error path string or int but got $element');
        }));
        final extensionsCode = errorJson
            .getObjectValueOrNull('extensions')
            ?.getObjectValueOrNull('code')
            ?.asStringOrNull();
        return GraphqlError(
          message: message ?? 'Unknown error',
          path: path,
          extensionsCode: extensionsCode,
        );
      }) ??
      const IListConst([]);

  return GraphqlResponse(
    jsonValue.getObjectValueOrThrow('data').asJsonObjectOrNull(),
    errors.isEmpty ? null : GraphqlErrors(errors),
  );
}