Skip to content

Feature request: Make Dependency Injection work for Middleware #8348

Description

@bdellegrazie

Use case

Hi,

Is there a way to extend the Dependency Injection support for routes to include middleware functions as well? Is this worthwhile?

Middleware is typically used to augment a request with additional data or implement a strict control and this is something that might require data access object (DAO) patterns or similar.

Thoughts?

Thanks in advance,

Brett

Solution/User Experience

Example :

Obviously this is a contrived example. As per the framework it would be possible to return an error response if any lookup failed rather than continuing on as this example does.

def user_middleware(
    app: APIGatewayHttpResolver,
    next_middleware: NextMiddleware,
    user_dao: Annotated[UserDao, Depends(get_user_dao)],
) -> Response:
    authorizer = app.current_event.request_context.authorizer
    if authorizer:
        sub: str | None = app.current_event.request_context.authorizer.jwt_claim.get("sub")
        if sub:
            user = user_dao.get(sub)
            if user:
                app.append_context(user=user)
    return next_middleware(app)

Alternative solutions

Acknowledgment

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions