From 614ca83d9348c8cd0f4b5a540e8f6f2e56ae43ad Mon Sep 17 00:00:00 2001 From: Ryan Booker <7423+ryanbooker@users.noreply.github.com> Date: Thu, 12 May 2022 10:13:00 +1000 Subject: [PATCH] Add Scheme parser and test --- Sources/URLRouting/Scheme.swift | 45 +++++++++++++++++++++ Tests/URLRoutingTests/URLRoutingTests.swift | 5 +++ 2 files changed, 50 insertions(+) create mode 100644 Sources/URLRouting/Scheme.swift diff --git a/Sources/URLRouting/Scheme.swift b/Sources/URLRouting/Scheme.swift new file mode 100644 index 0000000000..84992001e3 --- /dev/null +++ b/Sources/URLRouting/Scheme.swift @@ -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 + } +} diff --git a/Tests/URLRoutingTests/URLRoutingTests.swift b/Tests/URLRoutingTests/URLRoutingTests.swift index 85eea0c606..b7e5efbef9 100644 --- a/Tests/URLRoutingTests/URLRoutingTests.swift +++ b/Tests/URLRoutingTests/URLRoutingTests.swift @@ -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"))) {