M
Modular7mo ago
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]
## 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]()
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
Propose Middleware Solution by drujensen · Pull Request #33 · savio...
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 ...
2 Replies
artemiogr97
artemiogr977mo ago
I think you can do the following:
@value
struct RouterMiddleware[HTTPHandlerType: HTTPHandler](Middleware):
var next: Middleware
var routes: Dict[String, HTTPHandlerType]
@value
struct RouterMiddleware[HTTPHandlerType: HTTPHandler](Middleware):
var next: Middleware
var routes: Dict[String, HTTPHandlerType]
a2svior
a2sviorOP7mo ago
This is great, the error is gone! Thanks!
Want results from more Discord servers?
Add your server