graphql orderBy查询问题

时间:2018-03-23 21:49:04

标签: apollo graphql-js apollo-server

我正在使用apollo graphql服务器。我有一个非常无序的查询。

query feedQuery {
  allPostsFromAllBlogs
  {
    id
    blogId
    title
    text
    likes
    createdAt
  }
}

我想对结果进行排序(类型为[Post])。这是我用来做的那个查询:

query feedQuery {
  allPostsFromAllBlogs( orderBy: {field: createdAt, direction:DESC}) 
  {
    id
    blogId
    title
    text
    likes
    createdAt
  }
}

在graphiql中生成此输出:

{
  "errors": [
{
  "message": "Unknown argument \"orderBy\" on field \"allPostsFromAllBlogs\" of type \"Query\".",
  "locations": [
    {
      "line": 2,
      "column": 25
    }
    ]
   }
 ]
}

继承架构:

scalar DateTime
type Query {
  blogInfo(id: String): Blog
  post(id: String): Post
  topPost(blogId: String): Post
  allPosts(blogId: String): [Post]
  allPostsFromAllBlogs: [Post]
  topPostFromAllBlogs: [BlogWithPost]
  comments(postId: String): Comments
  allBlogs: [Blog]
}
type Mutation {
  createPost(title: String,
             content: String,
             type: String,
             blogId: String,
             avatar: String): Post
}
type Blog {
  id: String
  title: String
  description: String
  authorName: String
  avatar: String
}
type Post {
  id: String
  blogId: String
  title: String
  content: String
  likes: Int
  avatar: String
  createdAt: DateTime
  type: String
}
type BlogWithPost {
  id: String
  title: String
  description: String
  authorName: String
  avatar: String
  post: Post
}
type Comment {
  commenterId: String
  text: String
}
type Comments {
  postId: String
  comments: [Comment]
}

我不确定诊断问题需要哪些其他信息,但我认为它的查询语法错误。

为什么不识别orderBy?是否有不同或更好的方法对结果进行排序?

1 个答案:

答案 0 :(得分:0)

问题是因为allPostsFromAllBlogs没有任何输入类型(即过滤器)。在模式中可以看到:

type Query {
  ...
  allPosts(blogId: String): [Post]
  allPostsFromAllBlogs: [Post]
  ...
}

字段allPosts的输入类型为blogId: String,但是字段allPostsFromAllBlogs没有实现任何输入类型。

您必须将字段allPostsFromAllBlogs更改为以下内容:

type Query {
  ...
  allPosts(blogId: String): [Post]
  allPostsFromAllBlogs(orderBy: yourInputTypeDefinition): [Post]
  ...
}

您将不得不更改该字段的解析器。