Skip to content

Commit 29b8720

Browse files
authored
Add Scheme parser and test (#13)
1 parent 753431a commit 29b8720

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

Sources/URLRouting/Scheme.swift

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/// Parses a request's scheme.
2+
///
3+
/// Used to require a particular scheme at a particular endpoint.
4+
///
5+
/// ```swift
6+
/// Route(.case(SiteRoute.custom)) {
7+
/// Scheme("custom") // Only route custom:// requests
8+
/// ...
9+
/// }
10+
/// ```
11+
public struct Scheme: ParserPrinter {
12+
@usableFromInline
13+
let name: String
14+
15+
/// A parser of the `http` scheme.
16+
public static let http = Self("http")
17+
18+
/// A parser of the `https` scheme.
19+
public static let https = Self("https")
20+
21+
/// A parser of custom schemes.
22+
public static func custom(_ scheme: String) -> Self {
23+
Self(scheme)
24+
}
25+
26+
/// Initializes a scheme parser with a scheme name.
27+
///
28+
/// - Parameter name: A method name.
29+
@inlinable
30+
public init(_ name: String) {
31+
self.name = name
32+
}
33+
34+
@inlinable
35+
public func parse(_ input: inout URLRequestData) throws {
36+
guard let scheme = input.scheme else { throw RoutingError() }
37+
try self.name.parse(scheme)
38+
input.scheme = nil
39+
}
40+
41+
@inlinable
42+
public func print(_ output: (), into input: inout URLRequestData) {
43+
input.scheme = self.name
44+
}
45+
}

Tests/URLRoutingTests/URLRoutingTests.swift

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,11 @@ class URLRoutingTests: XCTestCase {
1212
XCTAssertEqual(try Method.post.print(), URLRequestData(method: "POST"))
1313
}
1414

15+
func testScheme() {
16+
XCTAssertNoThrow(try Scheme.http.parse(URLRequestData(scheme: "http")))
17+
XCTAssertEqual(try Scheme.http.print(), URLRequestData(scheme: "http"))
18+
}
19+
1520
func testPath() {
1621
XCTAssertEqual(123, try Path { Int.parser() }.parse(URLRequestData(path: "/123")))
1722
XCTAssertThrowsError(try Path { Int.parser() }.parse(URLRequestData(path: "/123-foo"))) {

0 commit comments

Comments
 (0)