JSON flutter 库升级后无法解析 GraphQL 响应

JSON fails to parse GraphQL response after flutter libs upgrade

我在 pubspec.yaml 中升级了软件包,看起来 JSON- 网络响应的解析现在已损坏。我从 graphql: ^3.1.0 迁移到 graphql: ^4.0.1 并且我还使用 json_annotation: ^3.1.0.

这是我从 http 客户端获得的响应的一个很好的示例,以及当我尝试将其作为字符串获取时所看到的内容:

如您所见,roles 数组不为空,它的 0 值不为空,但自从我升级了我的库后,这就是我在不更改任何其他代码的情况下得到的结果。

这是我的 GraphQL 查询文件:

query($pushCredential: TwilioPushCredential!) {
  user {
    id
    info {
      ...UserInfoFragment
    }
    roles {
      ... on Client {
        ...RoleUserFragment
        myFitnessPalId
      }
      ... on Coach {
        ...RoleUserFragment
        maxActiveClients
        inviteCode
      }
    }
    chatJwt(pushCredential: $pushCredential)
  }
}

fragment UserInfoFragment on UserInfo {
  email
  firstName
  lastName
  avatar
  phone
}

fragment RoleUserFragment on RoleUser {
  id
  role
}

以下是我处理响应的方式:

    final options = QueryOptions(
      document: get_user_info.document,
      variables: {'pushCredential': Platform.isIOS ? 'apn' : 'fcm'},
    );

    final result = await client.query(options);

    Logger.debug("getUser response: ${result.data['user']}");

看起来这个 ... on Client... on Coach 逻辑在新的 GraphQL 版本中不起作用。如何修复它,我做错了什么?

这是一个与缓存相关的错误,我们找到了解决方法:https://github.com/zino-hofmann/graphql-flutter/issues/994#issuecomment-1000748910

这可能很快就会得到解决,但我希望这个答案可以帮助一些人摆脱碎片问题。

此错误是由 graphql_flutter 中的 normalize 包更新引起的,特别是,normalize 需要您指定可能的类型映射才能使片段正常工作。这是从抽象联合和接口类型到它们的具体对象类型的映射。

interface PersonI {
  name: String
  age: Int
}
type Employee implements PersonI {
  name: String
  age: Int
  daysOfEmployement: Int
}
type InStoreCustomer implements PersonI {
  name: String
  age: Int
  numberOfPurchases: Int
}
type OnlineCustomer implements PersonI {
  name: String
  age: Int
  numberOfPurchases: Int
}
union CustomerU = OnlineCustomer | InStoreCustomer

可能的类型映射为:

const POSSIBLE_TYPES = const {
  'CustomerU': {'InStoreCustomer', 'OnlineCustomer'},
  'PersonI': {'Employee', 'InStoreCustomer', 'OnlineCustomer'},
}
// Here's how it's parsed to the cache
final client = GraphQLClient(
  cache: GraphQLCache(
    possibleTypes: POSSIBLE_TYPES,
  ),
)

您可以生成 POSSIBLE_TYPES 地图,例如,使用 graphql_codegen

此外,为了规范化以正确解析类型,您应该始终确保您正在查询 __typename。给定上面的示例,查询可能类似于

query {
  people {
    __typename # Needed to decide where which entry to update in the cache
    ... on Employee {
      name
      age
    }
    ... on Customer {
      name
      age
    }
  }
}

如果您不提供可能的类型映射并检查类型名称,则无法更新缓存。