Skip to content

Commit

Permalink
Add Scheme parser and test (#13)
Browse files Browse the repository at this point in the history
  • Loading branch information
ryanbooker authored May 20, 2022
1 parent 753431a commit 29b8720
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
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

0 comments on commit 29b8720

Please sign in to comment.