Get random item from Graphcool?

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

Alternatively, any tips for creating custom queries for Graphcool backends?

+4
source share
1 answer

The best way to do this is to use the API gateway template.

The idea behind this approach is to put the gateway server on top of the Graphcool CRUD API and thus configure the API. With this approach, you will write an additional resolver function that retrieves a 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)
          })
        },
      }
    },
  }),
})

. , :)

+4

Source: https://habr.com/ru/post/1688824/


All Articles