是否可以将 Apollo GraphQL 响应映射为单一类型?

问题描述

我有几个不同的突变和查询,它们返回一个 Profile 对象。我想创建一个由所有这些不同调用实现的单一 Profile 对象,而不是在调用的命名空间下嵌套类型的认 Apollo 行为。

现在:

SignInWithApple() -> SignInWithApple.Profile
SignInWithGoogle() -> SignInWithGoogle.Profile
SignInWithEmail() -> SignInWithEmail.Profile
GetProfile() -> GetProfile.Profile

想要:

SignInWithApple() -> Profile
SignInWithGoogle() -> Profile
SignInWithEmail() -> Profile
GetProfile() -> Profile

编辑* 到目前为止,我已经能够通过跳过 Apollo 生成的响应并将原始数据解码为我制作的 Profile 对象来完成此操作,但我仍然需要制作特殊的 DeCodable 容器,以便每个查询的命名空间/mutation 可以解包/移除。似乎必须有更好的方法......

解决方法

您可以使用 Union Interfaces 创建一个 Profile 类型,该类型可以是其中任何一个。

像这样

union Profile = SignInWithApple.Profile | 
  SignInWithGoogle.Profile |
  SignInWithEmail.Profile |
  GetProfile.Profile