Laravel Lighthouse GraphQL - Sorting on server side
Asked Answered
M

1

8

Hi I am new to GraphQL and I am trying to sort my data based on column content. I have an query endpoint where I can send:

query {
  user(count:20, firstName:"Foo") {
    data {
      name
      region
      birthDate
    }
  }
}

And the result is an array of 20 users with the first name Foo. But I want to order them by birthDate. I already tried so many things, but I just can not figure out. I already tried prepending sort and orderBy after the firstName, but I always get errors such as:

{
  "errors": [
    {
      "message": "Unknown argument \"sort\" on field \"user\" of type \"Query\".",
      "extensions": {
        "category": "graphql"
      },
      "locations": [
        {
          "line": 2,
          "column": 31
        }
      ]
    }
  ]
}

I am using Laravel Lighthouse as a wapper for GraphQL. I am surprised I could not find any information in regards on how to do this.

My query:

type Query {
    user(firstName: String @eq): [User!]! @paginate(type: "paginator" model: "App\\User")
}

type User {
    id: ID!
    firstName: String!
    lastName: String!
    birthDate: DateTime!
    email: String!
    created_at: DateTime!
    updated_at: DateTime!
}
Manifestation answered 14/7, 2019 at 14:38 Comment(0)
M
17

After searching for another hour, I finally found it. I updated my graphql file to this:

type Query {
    user(firstName: String @eq orderBy: [OrderByClause!] @orderBy): [User!]! @paginate(type: "paginator" model: "App\\User")
}

type User {
    id: ID!
    firstName: String!
    lastName: String!
    birthDate: DateTime!
    email: String!
    created_at: DateTime!
    updated_at: DateTime!
}

input OrderByClause{
    field: String!
    order: SortOrder!
}

enum SortOrder {
    ASC
    DESC
}

Now using this query will correctly sort them by birthDate:

query {
  user(count:20, firstName:"Foo", orderBy: [
        {
          field: "birthDate"
          order: DESC
        }
    ]) {
    data {
      name
      region
      birthDate
    }
  }
}
Manifestation answered 14/7, 2019 at 19:4 Comment(1)
thanks! this saved me from many more hours of angry searching. =)Boehm

© 2022 - 2024 — McMap. All rights reserved.