Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions Sources/URLRouting/Scheme.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/// Parses a request's scheme.
///
/// Used to require a particular scheme at a particular endpoint.
///
/// ```swift
/// Route(.case(SiteRoute.custom)) {
/// Scheme("custom") // Only route custom:// requests
/// ...
/// }
/// ```
public struct Scheme: ParserPrinter {
@usableFromInline
let name: String

/// A parser of the `http` scheme.
public static let http = Self("http")

/// A parser of the `https` scheme.
public static let https = Self("https")

/// A parser of custom schemes.
public static func custom(_ scheme: String) -> Self {
Self(scheme)
}

/// Initializes a scheme parser with a scheme name.
///
/// - Parameter name: A method name.
@inlinable
public init(_ name: String) {
self.name = name
}

@inlinable
public func parse(_ input: inout URLRequestData) throws {
guard let scheme = input.scheme else { throw RoutingError() }
try self.name.parse(scheme)
input.scheme = nil
}

@inlinable
public func print(_ output: (), into input: inout URLRequestData) {
input.scheme = self.name
}
}
5 changes: 5 additions & 0 deletions Tests/URLRoutingTests/URLRoutingTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ class URLRoutingTests: XCTestCase {
XCTAssertEqual(try Method.post.print(), URLRequestData(method: "POST"))
}

func testScheme() {
XCTAssertNoThrow(try Scheme.http.parse(URLRequestData(scheme: "http")))
XCTAssertEqual(try Scheme.http.print(), URLRequestData(scheme: "http"))
}

func testPath() {
XCTAssertEqual(123, try Path { Int.parser() }.parse(URLRequestData(path: "/123")))
XCTAssertThrowsError(try Path { Int.parser() }.parse(URLRequestData(path: "/123-foo"))) {
Expand Down