graphql-python / graphene-sqlalchemy

Graphene SQLAlchemy integration
http://docs.graphene-python.org/projects/sqlalchemy/en/latest/
MIT License
975 stars 225 forks source link

Question: How to access info in building relay.Node and connection #315

Closed shaozi closed 2 years ago

shaozi commented 2 years ago

It is convenient to just add two lines of code to do get by id and get all queries:

class EmployeeQuery(graphene.ObjectType):
    employee = relay.Node.Field(Employee)
    all_employees = SQLAlchemyConnectionField(Employee.connection, sort=Employee.sort_argument())

My question is, how do I enhance/customize the query so I can access the info for authorization purpose?

Currently I have to implement my own resolver, but for all_employees I lost the relay edges:

class EmployeeQuery(graphene.ObjectType):
    employee = graphene.Field(Employee, id=graphene.ID(required=True))
    def resolve_employee(parent, info, **args):
        id = args.get('id')
        print(f"resolve_employee: {id}, =========== user = {info.context.user}")
        return relay.Node.get_node_from_global_id(info, id, only_type=Employee)

    all_employees = graphene.List(Employee)
    def resolve_all_employees(parent, info, **args):
        print(f"resolve_all_employee: =========== user = {info.context.user}")
        return Employee.get_query(info).all() 

Is there a better more "graphene SQLAlchemy" way?

chrisberks commented 2 years ago

Use SQLAlchemyConnectionField and have your resolver return None.

class EmployeeQuery(graphene.ObjectType):
    all_employees = SQLAlchemyConnectionField(
        Employee.connection, sort=Employee.sort_argument()
    )

    def resolve_all_employees(parent, info, **args):
        print(f"resolve_all_employee: =========== user = {info.context.user}")
        return None

return None, return and omitting the return statement are equivalent.

shaozi commented 2 years ago

awesome! Thank you, it worked like a charm! Where is this documented?

erikwrede commented 2 years ago

I believe this is currently undocumented. Closing this, as documentation is another issue, the original problem seems to be solved. If you have further questions, feel free to open another issue!

github-actions[bot] commented 1 year ago

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related topics referencing this issue.