Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble with graphql orderBy query

I am using the apollo graphql server. I have a query that works well unordered.

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

I want to sort the results (of type [Post]). This is the query I'm using to do that:

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

Which produces this output in graphiql:

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

Heres the schema:

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]
}

I'm not sure what other information is needed to diagnose the problem, but I assume its a query syntax error.

Why is it not recognizing orderBy? Is there a different or better way to sort results?

like image 309
Kiera Avatar asked Oct 16 '22 20:10

Kiera


1 Answers

The issue is because allPostsFromAllBlogs does not have any input type (i.e. filters). As can be seen in the schema:

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

The field allPosts has input type blogId: String, but the field allPostsFromAllBlogs does not implement any input type.

You would have to change the field allPostsFromAllBlogs into something like:

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

And you would have to change the resolver for the field.

like image 119
Marco Daniel Avatar answered Oct 21 '22 07:10

Marco Daniel