Add Flag to Preserve GraphQL Queries After Extraction #35572
Unanswered
reilnuud
asked this question in
Ideas / Feature Requests
Replies: 1 comment 4 replies
-
hmmm less hacky than regex — babel would be consistently correct for parsing. A plugin could extract all the queries and write them out to files in the public folder e.g. |
Beta Was this translation helpful? Give feedback.
4 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Currently, there's no easy way to grab the contents of a GraphQL query during run time, or a way to access it during build and store it in the
pageContext
. There's probably a dozen different ways this could be implemented, and I would love to be corrected on this, but a few devs and I have gone back and forth on this one and we haven't found anything satisfactory.At the present time, the query gets extracted so trying to access the query just returns the hash instead of the query -- we just get a string of numbers tied to the response, the original query is nowhere to be found.
It makes sense to extract the queries and remove them from the bundle by default, they would add a few kb uncompressed depending on the number of different queries, however there are quite a few use cases where you'd want to access the query at runtime, the number one 1 use case being data preview which could look like this:
gatsby-config.js
SomePageComponent.js
The idea here is that usePreview checks the url for a token or preview url param (whatever your CMS uses) and then fetches the preview data inside a custom hook. The way we used to do this, we just copy-pasted the query and assign it to
previewQuery
and use it like usePreview( data, previewQuery) but this approach is less than ideal because if you make any changes to the schema or query, you'd need to update it in more than one place--not DRY, prone to errors, etc.Our new way of doing this is reading the files as text and using a regex to extract the query and then inject it into the pageContext during
createPages
. It's suuuuuper hacky, but it works, doesn't really impact the build time, and prevents the "forgot to copy-paste the query again" error.But, if we were to be able to grab the query from the page context after enabling this flag, then we wouldn't have these other issues -- the query is the exact same one we're using to build the page initially.
This approach would also remove the need to significantly refactor the query extraction process which say preserving the value of the
query
var would do.The one problem I can see in including the query in the
pageContext
is that page's data will grow by a few kb (uncompressed) -- especially for rather long queries. If there was some other way to store these so they only get loaded on-demand, that would be ideal.Beta Was this translation helpful? Give feedback.
All reactions