简体   繁体   English

GraphQL根查询:相同的架构,不同的类型

[英]GraphQL Root Query: Same schema, different types

I'm pretty new to GraphQL and within my root query I have two fields that are very similar aside from their "type" property, that I would like to combine. 我是GraphQL的新手,在我的根查询中,除了我的“ type”属性外,我还有两个要合并的字段。

allPosts returns an array of post objects, while post returns a single post. allPosts返回一个post对象数组,而post返回单个post。

Each field is using the same schema, and the loaders/resources are being determined within those respective fields based on the argument passed in. 每个字段都使用相同的架构,并且根据传入的参数在相应字段中确定装入程序/资源。

const RootQuery = new graphql.GraphQLObjectType({
    name: 'Query',
    description: 'Root Query',
    fields: {
      allPosts: {
          type: new graphql.GraphQLList(postType),
          args: {
              categoryName: {
                  type: graphql.GraphQLString
              }
          },
          resolve: (root, args) => resolver(args)
      },
      post: {
          type: postType,
          args: {
              slug: {
                  type: graphql.GraphQLString
              }
          },
          resolve: (root, args) => resolver(args)
      },
});

Is it possible to combine these two fields into one and have the type determined by the argument passed in or another variable? 是否可以将这两个字段组合为一个字段,并根据传入的参数或其他变量确定类型?

No, you can't! 不,你不能!

Once you define a field as GraphQLList , you always get an array. 一旦将字段定义为GraphQLList ,就总会得到一个数组。 There is no chance that you suddenly get an object instead of array of . 您不可能突然得到一个object而不是的array of Same apply to other case when you define field as GraphQLObjectType (or any other scalar type) and you want get an array as result. 当您将字段定义为GraphQLObjectType (或任何其他标量类型)并且想要获取数组作为结果时,同样适用于其他情况。

Those two fields have really different purposes. 这两个领域的目的确实不同。

Anyway, you can always add a limit logic to your allPosts field and limit the result to one. 无论如何,您始终可以在allPosts字段中添加一个限制逻辑,并将结果限制为一个。 But, nevertheless you get always array with only one post 但是,尽管如此,您总是只发表一篇文章

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

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