Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In GraphQL how to I query for a random record

Tags:

graphql

Let's say I have a Quote type. I'd like to be able to retrieve a random quote. I can get all the quotes using the following query:

query {
    allQuotes {
      id
      text
    }
  }

How do I get a random record from the Quotes

like image 600
Byron Avatar asked Oct 23 '25 05:10

Byron


1 Answers

It may be a good idea in your simplest case to just define getRandom resolver on the root-level Query type.

Another approach, given that you say you already have a Quote type defined, would be to define a resolver inside it.

Then, for the query from your example, the schema may resemble something like (I didn't test it):

type Quote {
  id: Int!
  text: String!
  getRandom(): Quote
}

type Query {
  allQuotes(): [Quote]
}

There is also a good example related to randomness in the official docs of GraphQL, try having a look at the Object Types section.

like image 182
nilfalse Avatar answered Oct 25 '25 02:10

nilfalse