-
Notifications
You must be signed in to change notification settings - Fork 53
Description
When multiple endpoints are defined, one ends up with:
await server.appendRoute(HTTPRoute(.GET, "/cat"), to: MyCatGetHandler())
await server.appendRoute(HTTPRoute(.GET, "/dog"), to: MyDogGetHandler())
await server.appendRoute(HTTPRoute(.GET, "/fish"), to: MyFishGetHandler())
and then implementations contains only the handler:
struct MyCatGetHandler : HTTPHandler {
func handleRequest(_ request: FlyingFox.HTTPRequest) async throws -> FlyingFox.HTTPResponse { }
}
struct MyDogGetHandler : HTTPHandler {
func handleRequest(_ request: FlyingFox.HTTPRequest) async throws -> FlyingFox.HTTPResponse { }
}
struct MyFishGetHandler : HTTPHandler {
func handleRequest(_ request: FlyingFox.HTTPRequest) async throws -> FlyingFox.HTTPResponse { }
}
Maybe it's my personal taste, but I find it better to have both the route and the handler in the same file, so by adding those extensions:
protocol RouteHandler : HTTPHandler {
func route() -> HTTPRoute
}
extension HTTPServer {
func appendRoutes(_ routeHandlers: RouteHandler...) {
routeHandlers.forEach {
appendRoute($0.route(), to: $0)
}
}
}
I'm able to write each handler like this (which I find convenient, specially when the route has placeholders, so I can write a single common function and define shared constants between the route and the request handler):
struct MyCatGetHandler : RouteHandler {
func route() -> HTTPRoute {
HTTPRoute(method: .GET, path: "/cat")
}
func handleRequest(_ request: FlyingFox.HTTPRequest) async throws -> FlyingFox.HTTPResponse {
// implementation
}
}
and also be able to add them all like this:
await server.appendRoutes(
MyCatGetHandler(),
MyDogGetHandler(),
MyFishGetHandler()
)
If you think it's a valuable addition, feel free to add it in the library 🍻
This is my third proposal so far (#50 #49), and the fact I was able to write everything I needed as an extension denotes really good design choices on your side, so kudos for the great work! 💯