Reputation: 325
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?
Upvotes: 4
Views: 521
Reputation: 22731
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 :)
Upvotes: 4