Advanced Sorting


With Prisma, it is possible to return lists of elements that are sorted (ordered) according to specific criteria. For example, you can order the list of Links alphabetically by their url or description. For the Hacker News API, you’ll leave it up to the client to decide how exactly it should be sorted and thus include all the ordering options from the Prisma API in the API of your GraphQL server. You can do so by creating an input type and an enum to represent the ordering options.

Add the following enum definition to your GraphQL schema:

input LinkOrderByInput {
  description: Sort
  url: Sort
  createdAt: Sort
enum Sort {

This represents the various ways that the list of Link elements can be sorted (asc = ascending, desc = descending).

Now, adjust the Query.feed field SDL again to include the orderBy argument:

type Query {
  info: String!
  feed(filterNeedle: String, skip: Int, take: Int, orderBy: LinkOrderByInput): [Link!]!
  me: User!

The implementation of the resolver is similar to what you just did with the pagination API.

Update the implementation of the feed resolver, change the imports and pass the orderBy argument along to Prisma:

import { Link, Prisma, User } from '@prisma/client'
const resolvers = {
  // ... other resolvers ...
  Query: {
    // ... other resolvers ...
      parent: unknown,
      args: {
        filter?: string
        skip?: number
        take?: number
        orderBy?: {
          description?: Prisma.SortOrder
          url?: Prisma.SortOrder
          createdAt?: Prisma.SortOrder
      context: GraphQLContext
    ) {
      const where = args.filter
        ? {
            OR: [{ description: { contains: args.filter } }, { url: { contains: args.filter } }]
        : {}
        skip: args.skip,
        take: args.take,
        orderBy: args.orderBy

Awesome! Here’s a query that sorts the returned links by their creation dates:

query {
  feed(orderBy: { createdAt: asc }) {