graphql-query icon indicating copy to clipboard operation
graphql-query copied to clipboard

Add functionality to pass context while rendering

Open safwanrahman opened this issue 1 year ago • 2 comments

Hi, First of all, Thanks a lot for the package 🚀. It is very nice to have this kind of DSL for GraphQL.

Currently I am working on a project where I need to have one optional argument according to the logic. We need to decide to render the argument only the time when we are rending the whole query.

So it would be nice to pass some context while rendering. Therefore, we can extend the Argument overwrite the template to not render the argument if flag is True in the context.

So it can be like following

In jinja template:

// optional_argument.jinja2
{% if ctx.render_foo_field %}
{{ name }}: {
  {{ value }}
}
{% endif %}
class OptionalArgument(Argument):
    template = "optional_argument.jinja2"
    def render(self, context=None):
        template = template_env.get_template(self.template)
        return template.render(name=self.name, value=self.value, ctx=context)

query = Query(name="bar", arguments=OptionalArgument(name="foo", value="bar")

print(query.render(context={"render_foo_field": True}))
# This query is with the foo field argument

print(query.render(context={"render_foo_field": False}))
# This one will not have foo field as argument

What do you think? If you are interested, I can make a PR

safwanrahman avatar Sep 01 '23 09:09 safwanrahman