Alter graphql data just before templates are rendered.

Created on 31 October 2019, over 4 years ago
Updated 29 September 2023, 9 months ago

Shortly after I started to work with GraphQL Twig contrib I've realized that the shape of GraphQl query results does not allign as well with my components. I needed to re-shape the GraphQL query result to fit my structure (remove some nested paths).

The best solution I was able to come with is to alter GraphQL result data in GraphQLTemplateTrait.php (https://git.drupalcode.org/project/graphql_twig/blob/8.x-1.x/src/GraphQL...) just before they are sent over to the template itself. Re-shaping the PHP array seems to be simple enough and with some comments in each Twig template (to explain where and how the data are being shaped) should be obvious.

I will attach patch soon (finishing some testing).

What I've tried before I settled down with the solution: "alter GraphQL result data via hook before rendering"
1.) Provide a _get and _root fields on every GraphQL object and Root to be able to:
a.) query deeper nested values with just one label
b.) create more level nested label
Basically trying to get PHP implementation of GraphQL Leveler: Controlling Shape In The Query https://www.fourkitchens.com/blog/development/graphql-leveler-controllin... (code: Graphql-leveler https://github.com/chasingmaxwell/graphql-leveler), but it turned out to be pretty difficult and could introduce unforseen bugs.
2.) Provide a markup into the GraphQL query to know how do we want to process it, remove and save the instructions and then process it before handing over to webonyx/graphql-php library (https://github.com/webonyx/graphql-php) and reshape it with collected instructions after getting GraphQL query result. It would mean to kind of rework the JavaScript solution: GraphQL Lodash https://github.com/APIs-guru/graphql-lodash. Basically just parsing the query by Parser from webonyx/graphql-php library (https://github.com/webonyx/graphql-php). Still quite difficult.

Realizations:
* Each GraphQL object/type has its resolver (most usually a callback/callable in form of function or method).
* I could use resolvers one by one to get a value for the whole nested path (I've got the feeling that the drupal/graphql implementation and webonyx/graphql-php library doesn't have a functionality decoupled enough to do this easily.

I'm happy to hear your ideas.

✨ Feature request
Status

Fixed

Component

Code

Created by

πŸ‡¦πŸ‡ΊAustralia dabbor

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.69.0 2024