【问题标题】:Pattern for multiple types from GraphQL Union来自 GraphQL Union 的多种类型的模式
【发布时间】:2020-10-15 06:38:49
【问题描述】:

我正在学习 GraphQL 中的接口和联合(使用 Apollo Server)并且想知道一些事情。使用文档示例https://www.apollographql.com/docs/apollo-server/schema/unions-interfaces/#union-type,我将如何返回可以返回作者和书籍的结果?

我的理解是你只能返回一种对象类型。如果搜索结果包含书籍和作者的数组,那么如何返回这样的结果?可以为这种情况安排事情吗?我注意到__resolveType 不适用于数组,只能返回一个结果(它将返回数组中所有对象的类型,而不是数组中的每个对象)。

GraphQL 类型定义

const { gql } = require('apollo-server');

const typeDefs = gql`
  union Result = Book | Author

  type Book {
    title: String
  }

  type Author {
    name: String
  }

  type Query {
    search: [Result]
  }
`;

解析器

const resolvers = {
  Result: {
    __resolveType(obj, context, info){
      console.log(obj);
      if(obj.name){
        return 'Author';
      }

      if(obj.title){
        return 'Book';
      }

      return null;
    },
  },
  Query: {
    search: () => { ... }
  },
};

const server = new ApolloServer({
  typeDefs,
  resolvers,
});

server.listen().then(({ url }) => {
  console.log(`???? Server ready at ${url}`)
});

实际的 GraphQL 查询可能看起来像这样,并且考虑到搜索结果既是书籍又是作者:

{
  search(contains: "") {
    ... on Book {
      title
    }
    ... on Author {
      name
    }
  }
}

运行时,__resolveType(obj, context, info){obj 是:

[{ title: 'A' }, { title: 'B' }, { name: 'C' }]

【问题讨论】:

    标签: graphql apollo-server


    【解决方案1】:

    只有两种方式会发生:

    1. search 字段的类型实际上不是一个列表(即,它是 Result 而不是上面代码中显示的 [Result]
    2. search 字段的解析器正在返回对象数组的数组:return [[{ title: 'A' }, { title: 'B' }, { name: 'C' }]]

    【讨论】:

    • 我通过console.log(obj)输出结果,得到[{ title: 'A' }, { title: 'B' }, { name: 'C' }]
    • 谢谢丹尼尔(再次?)我在我的架构中发现了问题。在TypeDef,上面是search: [Result],我的基本上是search: Result,所以它不是一个数组而是一个完整的对象。很高兴你和我在一起!
    猜你喜欢
    • 2019-08-19
    • 1970-01-01
    • 2018-11-21
    • 2020-02-05
    • 1970-01-01
    • 2019-03-25
    • 2018-01-30
    • 2019-06-27
    • 2020-04-21
    相关资源
    最近更新 更多