Skip to content

Commit

Permalink
Added middleware support to top level and host groups
Browse files Browse the repository at this point in the history
  • Loading branch information
dimitribouniol committed Jan 11, 2024
1 parent ded511d commit 617adc9
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions Sources/HostRouter/HostMiddlewareGroup.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import Vapor

struct HostMiddlewareGroup: Sendable, TopLevelHostRoutesBuilder {
/// Router to cascade to.
let root: HostRoutesBuilder

/// Additional middleware.
let middleware: [Middleware]

/// Creates a new routing group.
init(root: HostRoutesBuilder, middleware: [Middleware]) {
self.root = root
self.middleware = middleware
}

/// Prepend the root to the added route, and pass it up the chain.
func add(_ route: HostRoute) {
route.route.responder = self.middleware.makeResponder(chainingTo: route.route.responder)
root.add(route)
}
}

extension TopLevelHostRoutesBuilder {
public func grouped(_ middleware: Middleware...) -> some TopLevelHostRoutesBuilder {
HostMiddlewareGroup(root: self, middleware: middleware)
}

public func grouped(_ middleware: [Middleware]) -> some TopLevelHostRoutesBuilder {
HostMiddlewareGroup(root: self, middleware: middleware)
}

public func group(_ middleware: Middleware..., configure: (TopLevelHostRoutesBuilder) throws -> ()) rethrows {
try configure(HostMiddlewareGroup(root: self, middleware: middleware))
}

public func group(_ middleware: [Middleware], configure: (TopLevelHostRoutesBuilder) throws -> ()) rethrows {
try configure(HostMiddlewareGroup(root: self, middleware: middleware))
}
}

extension HostRoutesBuilder {
public func grouped(_ middleware: Middleware...) -> some HostRoutesBuilder {
HostMiddlewareGroup(root: self, middleware: middleware)
}

public func grouped(_ middleware: [Middleware]) -> some HostRoutesBuilder {
HostMiddlewareGroup(root: self, middleware: middleware)
}

public func group(_ middleware: Middleware..., configure: (HostRoutesBuilder) throws -> ()) rethrows {
try configure(HostMiddlewareGroup(root: self, middleware: middleware))
}

public func group(_ middleware: [Middleware], configure: (HostRoutesBuilder) throws -> ()) rethrows {
try configure(HostMiddlewareGroup(root: self, middleware: middleware))
}
}

0 comments on commit 617adc9

Please sign in to comment.