strawberry-graphql / strawberry

A GraphQL library for Python that leverages type annotations 🍓
https://strawberry.rocks
MIT License
4.04k stars 535 forks source link

FastAPI Parametric Dependency Injection #2183

Open csuriano23 opened 2 years ago

csuriano23 commented 2 years ago

Hello, is there a way to define a parametric dependency injection based on some of the query/mutation variables?

Eg. something like

def custom_context_dependency(name: str) -> str:
    return name

async def get_context(
    custom_value=Depends(custom_context_dependency),
):
    return {
        "custom_value": custom_value,
    }

@strawberry.type
class Query:
    @strawberry.mutation
    def example(self, name: str, info: Info) -> str:
        return f"Hello {info.context['custom_value']}"

Upvote & Fund

Fund with Polar

nrbnlulu commented 2 years ago

You want to inject stuff into info.context? if yes, when?

csuriano23 commented 2 years ago

Yes, I want to inject an http client as a dependency in the info.context, but some client parameters depends on the request parameter (eg. the login user)

nrbnlulu commented 2 years ago

You can:

patrick91 commented 2 years ago

maybe @Kludex has some ideas about this. In the django integration we have defined get_context on the class and it receives the info param, I think we should have the same for fastapi

Kludex commented 2 years ago

Why not having the HTTP client globally? 🤔

csuriano23 commented 2 years ago

Why not having the HTTP client globally? 🤔

It would mean having a singleton per HTTP user session; I am not sure it really is the best thing

Luferov commented 2 years ago

This is a great idea. I would suggest writing an extension that injects the fastapi dependency into the resolvers.