#Passing a trait as a parameter to `Dict`?

3 messages · Page 1 of 1 (latest)

flint cloud
#

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 ...

uncut adderBOT
#

To help others find answers, you can mark your question as solved via Right click solution message -> Apps -> ✅ Mark Solution

polar kestrel
#

I think you can do the following:

@value
struct RouterMiddleware[HTTPHandlerType: HTTPHandler](Middleware):
    var next: Middleware
    var routes: Dict[String, HTTPHandlerType]