ModularM
Modular2y ago
3 replies
a2svior

Passing a trait as a parameter to `Dict`?

This is related to a proposal for adding Middleware functionality to Lightbug HTTP: https://github.com/saviorand/lightbug_http/pull/33#issuecomment-2105547981
We're trying to do something like the following:
## HTTPHandler is an interface for handling HTTP requests in the RouterMiddleware.
## It is a leaf node in the middleware chain.
trait HTTPHandler:
    fn handle(self, context: Context) -> HTTPResponse:
        ...

## Router middleware routes requests to different middleware based on the path.
@value
struct RouterMiddleware(Middleware):
    var next: Middleware
    var routes: Dict[String, HTTPHandler]

Where routes: Dict[String, HTTPHandler] takes in an HTTPHandler trait which can be implemented by different handlers, including ones created by the user.
Currently, since Dict expects a value that implements CollectionElement, so we're getting the following error:
middleware/router.mojo:15:36: error: 'Dict' parameter #1 has 'CollectionElement' type, but value has type 'AnyTrait[HTTPHandler]'
        self.routes = Dict[String, HTTPHandler]()

This persists even if HTTPHandler extends CollectionElement like so:
trait HTTPHandler(CollectionElement).

Any ideas on how we can get this to work?
GitHub
This is a proposal and code sample for adding middleware to the light bug project.
Proposal
The chain of responsibility design pattern is used to chain together pieces of middleware that will each ...
Propose Middleware Solution by drujensen · Pull Request #33 · savio...
Was this page helpful?