GraphQL nested query arguments?

1.2k views Asked by At

When building a GraphQL API, is it possible to allow arguments on nested query properties? i.e. I've implemented an orderBy arg for a top-level tasks query like so:

query {
  tasks(orderBy: { order: asc }) {
    title
  }
}

and this works fine, but I would like to be able to query a collection of tasks and add the query arguments to the nested tasks property like this:

query {
  collection {
    id
    name
    tasks(orderBy: { order: asc }) {
      title
    }
  }
}

It doesn't recognize the arguments by default, so I assume if it is possible, then there is some further set up required. I get this error when I try that query: "Unknown argument \"orderBy\" on field \"tasks\" of type \"Collection\"."

P.S. I'm using graphql-yoga with prisma on the backend.

2

There are 2 answers

0
Mickaël Boidin On

Do you use nexus/schema and nexus-plugin-prisma ? If you do, you have to activate ordering in your collection task model like this t.model.tasks({ ordering: true })

0
mrseanbaines On

Aha! I worked it out in the end. I just needed to pass the args to the tasks invocation in the Collection.tasks resolver:

Collection: {
  tasks: (parent, args, context) => {
    const { id } = parent

    const collection = context.prisma.collection.findOne({
      where: { id },
    })

    return collection.tasks(args) // ← pass in `args` here
  },
},

I also needed to add the orderBy option in my schema for the Collection.tasks field (I previously only had it on Query.tasks)