简体   繁体   English

在 Flutter 的 Ferry Graphql 中序列化标量 JSON 以实现灵活查询

[英]Serializing scalar JSON in Flutter's Ferry Graphql for flexible Query

I have the following JSON scalar:我有以下 JSON 标量:

"""
The `JSON` scalar type represents JSON values as specified by [ECMA-404](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf).
"""
scalar JSON

which I am trying to convert since my query is accepting input: JSON .我正在尝试转换,因为我的query正在接受input: JSON When testing using graphql playground, query is JSON object thus the following works:当使用 graphql 操场进行测试时,查询是 JSON object 因此以下工作:

query {
  carts(where: {
    owner:{id: "xxx"}
    store:{name: "yyy"}
  }) {
    id
  }
}
# query is the starting from the where: {...}
# build.yaml
# build.yaml
gql_build|schema_builder: #same for gql_build|schema_builder + gql_build|var_builder + ferry_generator|req_builder:
  options:
          type_overrides:
            DateTime:
              name: DateTime
            JSON:
              name: BuiltMap<String, dynamic>
              import: 'package:built_collection/built_collection.dart'
gql_build|serializer_builder:
        enabled: true
        options:
          schema: myapp|lib/graphql/schema.graphql
          custom_serializers:
            - import: 'package:myapp/app/utils/builtmapjson_serializer.dart'
              name: BuiltMapJsonSerializer

This is the custom serializer (builtmapjson_serializer.dart)这是自定义序列化程序(builtmapjson_serializer.dart)

//// lib/app/utils/builtmapjson_serializer.dart
import 'package:built_collection/built_collection.dart';
import "package:gql_code_builder/src/serializers/json_serializer.dart";

class BuiltMapJsonSerializer extends JsonSerializer<BuiltMap<String, dynamic>> {
  @override
  BuiltMap<String, dynamic> fromJson(Map<String, dynamic> json) {
    print('MyJsonSerializer fromJson: $json');
    return BuiltMap.of(json);
  }

  @override
  Map<String, dynamic> toJson(BuiltMap<String, dynamic> operation) {
    print('MyJsonSerializer toJson: ${operation.toString()}');
    return operation.asMap();
  }
}

and the usage:和用法:

Future testQuery() async {
    Map<String, dynamic> queryMap = {
      "where": {
        "owner": {
          "id": "xxx",
          "store": {"name": "yyy"}
        }
      }
    };
    final req = GFindCartsReq((b) {
      return b..vars.query.addAll(queryMap);
    });
    var resStream = _graphQLService.client.request(req);
    var res = await resStream.first;
    print(
        'linkExceptions: ${res.linkException}'); // Map: LinkException(Bad state: No serializer for '_InternalLinkedHashMap<String, Map<String, Object>>'.)
  }

So whenever I try to query, it is throwing the linkException stated in the comment on the last line of usage.因此,每当我尝试查询时,它都会抛出最后一行使用的注释中说明的 linkException。 Any idea what should be the way of serializing it?知道序列化它的方式应该是什么吗?

// Write query like this
query FindCarts($owner_id: String!, $store_name: String!) {
  carts(where: {
    owner:{id: $owner_id}
    store:{name: $store_name}
  }) {
    id
  }
}
// And make request like this:
final req = GFindCartsReq((b) => b..vars.store_name = 'XXX'..vars.owner_id = 'YYY');

I think you may be misunderstanding the use case.我认为您可能误解了用例。 they are there to serialize and deserialize the response if you want to end up with a Dart object that's different from graphql representation.如果你想得到一个不同于 graphql 表示的 Dart object ,它们可以序列化和反序列化响应。 you may want to try rereading this section: https://ferrygraphql.com/docs/custom-scalars/#create-a-custom-serializer您可能想尝试重读本节: https://ferrygraphql.com/docs/custom-scalars/#create-a-custom-serializer

in the example in the docs, the graphql schema returns an int for the timestamp, but we want to actually use a Date object, so that's the purpose of the serializer.在文档中的示例中,graphql 模式返回一个 int 作为时间戳,但我们希望实际使用日期 object,这就是序列化程序的目的。 it tells ferry to deserialize the int in our responses to a Date so we can use a Date in our dart code.它告诉 ferry 反序列化我们对 Date 的响应中的 int,以便我们可以在 dart 代码中使用 Date。 you could still use a json serializer (like in the examples you linked to) but it still would not be in the way you're trying to use it -- it would be if your schema returns a json string and you want to deserialize the json string.您仍然可以使用 json 序列化程序(如您链接到的示例中),但它仍然不会妨碍您尝试使用它 - 如果您的架构返回 json 字符串并且您想要反序列化json 字符串。 for example, in my case, my graphql schema actually does return a "jsonb" type on some objects.例如,在我的情况下,我的 graphql 模式实际上确实在某些对象上返回了“jsonb”类型。 in order to handle that, i'm using built_value's default json_object like this:为了处理这个问题,我使用了 built_value 的默认 json_object,如下所示:

(
...
          type_overrides:
            jsonb:
              name: JsonObject
              import: "package:built_value/json_object.dart"
          custom_serializers:
            - import: "package:built_value/src/json_object_serializer.dart"
              name: JsonObjectSerializer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM