rsnext/examples/with-graphql-hooks/lib/graphql-request.js
Luis Alvarez D b4ec992815
[Examples] Move with-graphql-hooks to SSG (#13858)
Related to https://github.com/vercel/next.js/issues/11014

The setup is very similar to the one used for Apollo examples.

@Joezo I've removed the demo example that you added to the readme (https://github.com/vercel/next.js/pull/6482) as it will be outdated after this PR is merged.
2020-06-08 16:23:34 +00:00

30 lines
949 B
JavaScript

const defaultOpts = { useCache: true }
/**
* Returns the result of a GraphQL query. It also adds the result to the
* cache of the GraphQL client for better initial data population in pages.
*
* Note: This helper tries to imitate what the query hooks of `graphql-hooks`
* do internally to make sure we generate the same cache key
*/
export default async function graphQLRequest(client, query, options) {
const opts = { ...defaultOpts, ...options }
const operation = {
query,
variables: opts.variables,
operationName: opts.operationName,
persisted: opts.persisted,
}
if (opts.persisted || (client.useGETForQueries && !opts.isMutation)) {
opts.fetchOptionsOverrides = {
...opts.fetchOptionsOverrides,
method: 'GET',
}
}
const cacheKey = client.getCacheKey(operation, opts)
const cacheValue = await client.request(operation, opts)
client.saveCache(cacheKey, cacheValue)
return cacheValue
}