4

Is it possible to return a random graphql element from a Graphcool backend? If so, how could this be done?

Alternatively, any tips on howto create custom queries for Graphcool backends?

nburk
  • 22,409
  • 18
  • 87
  • 132
William Pfaffe
  • 305
  • 4
  • 16

1 Answers1

4

The best way to do this is by using the API Gateway pattern.

The idea of that approach is to put a gateway server on top of Graphcool's CRUD API and thus customize the API. With this approach, you'd write an additional resolver function that retrieves the random element for you:

const extendTypeDefs = `
  extend type Query {
    randomItem: Item
  }
`

const mergedSchemas = mergeSchemas({
  schemas: [graphcoolSchema, extendTypeDefs],
  resolvers: mergeInfo => ({
    Query: {
      randomItem: {
        resolve: () => {
          return request(endpoint, allItemsQuery).then(data => {
            const { count } = data._allItemsMeta
            const randomIndex = Math.floor((Math.random() * (count-1)) + 0)
            const { id } = data.allItems[randomIndex]
            return request(endpoint, singleItemQuery, { id }).then(data => data.Item)
          })
        },
      }
    },
  }),
})

I created a full example of this here. Let me know if you have any additional questions :)

nburk
  • 22,409
  • 18
  • 87
  • 132
  • 1
    Thank you. Been trying different methods on the playground to write queries that could do so, but never got anywhere with it. – William Pfaffe Nov 07 '17 at 14:09
  • Is there a way to get the modules to work in react native? Or would this change the code substantially? Keep getting that graphql tools isnt made for React Native. – William Pfaffe Nov 07 '17 at 16:13
  • 1
    This code is not supposed to live in the client, but in the server side. – marktani Nov 07 '17 at 17:07
  • Hey @Michal, thanks for the feedback :) I removed the broken link from the answer. Also, the the GraphQL server that exposes that query can easily be deployed to AWS Lambda or some other sls provider, so I do think it is serverless – nburk Apr 17 '18 at 10:12
  • 1
    Thank you for the effort :) I did not mean to be rude. Your answer is probably the best thing that OP can do in order to get random items from graphcool. However pure graphcool solution (without any server configuration) is currently not possible. – Michal Apr 17 '18 at 15:01
  • All good, thanks for pointing out the broken link anyways! :) – nburk Apr 18 '18 at 15:06