avanov / graphql-dsl

Compose GraphQL queries by composing Python types!
https://graphql-dsl.rtfd.io/
MIT License
5 stars 2 forks source link

Set name of query dynamically #9

Open iwconfig opened 1 year ago

iwconfig commented 1 year ago

I'd like to be able to change the name of the class as it's represented in the query.

Example:

class HeroAndDroid(NamedTuple):
    hero: Hero
    droid: Droid

and instead of

print(GQL(QUERY | HeroAndDroid).query)

# 'query HeroAndDroid{hero{name}droid{name}}'

I'd like to do something like

print(GQL(QUERY | HeroAndDroid * AS * 'asdf').query)

# 'query asdf{hero{name}droid{name}}'

or

print(GQL(QUERY | HeroAndDroid * AS * ANONYMOUS).query)

# 'query {hero{name}droid{name}}'

Of course I can do it like this

#RENAME = lambda cls, name: type(name, (cls,), {})
RENAME = lambda cls, name: (setattr(cls, '__name__', name), cls)[-1]

print(GQL(QUERY | RENAME(HeroAndDroid, 'I_Prefer_This_Name')).query)

# 'query I_Prefer_This_Name{hero{name}droid{name}}'

but I think using the AS function for this is much more suitable.

iwconfig commented 1 year ago

A possible solution:

@mul_infix
def AS(a: Binding, b: str) -> Binding:
    if isinstance(a, Binding):
        return a._replace(variable_alias=b)
    a.__name__ = b
    return a

Not sure if it's enough though but it works fine with my basic example