1

我正在尝试使用 Flutter、Chopper 和 Built Value 向 Hasura 后端发出请求,但出现以下错误

> When parsing the constructor GQLReq of type Hasura.GraphQL.Transport.HTTP.Protocol.GQLReq expected Object but got String.,

斩波器服务

@ChopperApi(baseUrl: '/v1/graphql')
abstract class PostApiService extends ChopperService {
  @Post()
  Future<Response<BuiltPost>> get(@Body() String body);

  static PostApiService create(AuthHeaderProvider authHeaderProvider) {
    final client = ChopperClient(
      baseUrl: 'https://arrivee-app-test.herokuapp.com',
      services: [
        _$PostApiService(),
      ],
      converter: BuiltValueConverter(),
      interceptors: [
        HttpLoggingInterceptor(),
     //   HeadersInterceptor({'content-type': 'application/json'}),
        HeadersInterceptor({'Authorization':'Bearer token'})
      ],
    );
    return _$PostApiService(client);
  }
}

我使用以下代码提出请求

    var request = RequestModel((b) => b
  ..query = fetchAccommodations()
  ..variables = null
  ..operationName = 'AccommodationGet');

var response = await client.get(request.toJson());

请求模型

    abstract class RequestModel
    implements Built<RequestModel, RequestModelBuilder> {
  String get query;

  @nullable
  String get variables;

  String get operationName;

  RequestModel._();

  factory RequestModel([updates(RequestModelBuilder b)]) = _$RequestModel;

  String toJson() {
    return json
        .encode(serializers.serializeWith(RequestModel.serializer, this));
  }

  static RequestModel fromJson(String jsonString) {
    return serializers.deserializeWith(
        RequestModel.serializer, json.decode(jsonString));
  }

  static Serializer<RequestModel> get serializer => _$requestModelSerializer;
}
4

2 回答 2

0

我设法解决了它。在此处发布以供将来参考。我让 chopper 进行从模型到字符串的转换,而不是事先手动进行,在这里我将 chopper 服务的签名从:

 @Post()
  Future<Response<BuiltPost>> get(@Body() String body);

@Post()
Future<Response<BuiltPost>> get(@Body() RequestModel body);

并从以下位置调用服务:

 var request = RequestModel((b) => b
  ..query = fetchAccommodations()
  ..variables = null
  ..operationName = 'AccommodationGet');

var response = await client.get(request.toJson());

 var request = RequestModel((b) => b
      ..query = fetchAccommodations()
      ..variables = null
      ..operationName = 'AccommodationGet');

var value = await client.get(request);
于 2020-04-12T18:28:54.923 回答
0

尝试在 Angular Dart 中对 Hasura 进行简单的 http POST 调用时遇到了同样的错误(没有可用的 GraphQL 客户端)。

我发现必须按以下方式构建 Json 字符串:

   String query = """
      {
        account {
            id
          }
      }
    """;

    Map<String, dynamic> variables;

    if (query.trimLeft().split(' ')[0] != 'query') {
      query = 'query $docQuery';
    }

    var jsonMap = {'query': query, 'variables': variables};

    final _headers = {'Content-Type': 'application/json'};
    return _authHttpService.post(_apiUrl,
        headers: _headers, body: json.encode(jsonMap));

希望它可以帮助任何寻找香草飞镖解决方案的人。

于 2020-04-19T20:19:27.077 回答