0
0
GraphqlHow-ToBeginner · 4 min read

How to Implement Sorting in GraphQL Queries Easily

To implement sorting in GraphQL, define a sorting argument in your query schema, often using an enum to specify fields and order directions. Then, use this argument in your resolver to order the data before returning it.
📐

Syntax

Sorting in GraphQL is done by adding an argument to your query that specifies the sort field and direction. Typically, you define an enum type for sorting options and add it as an argument to your query field.

The resolver uses this argument to sort the data accordingly before returning it.

graphql
enum SortOrder {
  ASC
  DESC
}

enum UserSortField {
  NAME
  AGE
}

type Query {
  users(sortField: UserSortField, sortOrder: SortOrder): [User]
}
💻

Example

This example shows a GraphQL schema with sorting arguments and a resolver that sorts a list of users by name or age in ascending or descending order.

javascript
const { ApolloServer, gql } = require('apollo-server');

const typeDefs = gql`
  enum SortOrder {
    ASC
    DESC
  }

  enum UserSortField {
    NAME
    AGE
  }

  type User {
    id: ID!
    name: String!
    age: Int!
  }

  type Query {
    users(sortField: UserSortField, sortOrder: SortOrder): [User!]!
  }
`;

const usersData = [
  { id: '1', name: 'Alice', age: 30 },
  { id: '2', name: 'Bob', age: 25 },
  { id: '3', name: 'Charlie', age: 35 }
];

const resolvers = {
  Query: {
    users: (_, { sortField, sortOrder }) => {
      if (!sortField) return usersData;
      const sorted = [...usersData].sort((a, b) => {
        let fieldA = a[sortField.toLowerCase()];
        let fieldB = b[sortField.toLowerCase()];
        if (fieldA < fieldB) return sortOrder === 'DESC' ? 1 : -1;
        if (fieldA > fieldB) return sortOrder === 'DESC' ? -1 : 1;
        return 0;
      });
      return sorted;
    }
  }
};

const server = new ApolloServer({ typeDefs, resolvers });

server.listen().then(({ url }) => {
  console.log(`Server ready at ${url}`);
});
Output
Server ready at http://localhost:4000/
⚠️

Common Pitfalls

  • Not defining sorting enums can lead to unclear or inconsistent sorting options.
  • Forgetting to handle the case when no sorting argument is provided may cause errors or unexpected order.
  • Sorting on fields not included in the schema or resolver logic will fail.
  • Sorting logic in resolvers must handle both ascending and descending orders explicitly.
graphql
/* Wrong: No enum, no default handling */

type Query {
  users(sortField: String): [User]
}

// Resolver might fail or sort unpredictably

/* Right: Use enums and default fallback */

enum SortOrder {
  ASC
  DESC
}

enum UserSortField {
  NAME
  AGE
}

// Resolver checks for undefined and uses default sorting
📊

Quick Reference

Use these tips to implement sorting in GraphQL:

  • Define enum types for sort fields and order.
  • Add sorting arguments to your query fields.
  • Implement sorting logic in resolvers using these arguments.
  • Handle cases when sorting arguments are missing.
  • Test sorting with different fields and orders.

Key Takeaways

Define sorting enums for clear and limited sorting options.
Add sorting arguments to your GraphQL query fields.
Implement sorting logic in resolvers using the arguments.
Always handle cases where sorting arguments are missing.
Test sorting thoroughly with different fields and orders.