Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Lighthouse GraphQL - Sorting on server side

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!
}
like image 561
TheKeymaster Avatar asked Jul 14 '19 14:07

TheKeymaster


Video Answer


1 Answers

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
    }
  }
}
like image 59
TheKeymaster Avatar answered Nov 15 '22 02:11

TheKeymaster