-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathRouteMatcher.swift
More file actions
209 lines (168 loc) · 6.02 KB
/
RouteMatcher.swift
File metadata and controls
209 lines (168 loc) · 6.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
//
// RouteMatcher.swift
// Meridian
//
// Created by Soroush Khanlou on 8/28/20.
//
import Foundation
func normalizePath(_ string: String) -> String {
return normalizePath(string.split(separator: "/"))
}
func normalizePath(_ path: [Substring]) -> String {
var result = path.joined(separator: "/")
if !result.starts(with: "/") {
result.insert("/", at: result.startIndex)
}
return result
}
public struct MatchedRoute: Sendable {
let parameters: [String: Substring]
public init(parameters: [String: Substring] = [:]) {
self.parameters = parameters
}
public func parameter<Key: URLParameterKey>(for key: Key.Type) throws -> Key.DecodeType {
guard let substring = self.parameters[Key.stringKey] else {
throw MissingURLParameterError()
}
let value = String(substring)
if Key.DecodeType.self == String.self {
return value as! Key.DecodeType
} else if let finalValue = Key.DecodeType(value) {
return finalValue
} else {
throw URLParameterDecodingError(type: Key.DecodeType.self)
}
}
}
public indirect enum RouteMatcher: Sendable {
case any
case root
case path(String)
case interpolated(InterpolatedPath)
case custom(matches: @Sendable (RequestHeader) -> MatchedRoute?)
case method(HTTPMethod, RouteMatcher)
case multiple([RouteMatcher])
public init(matches: @Sendable @escaping (RequestHeader) -> MatchedRoute?) {
self = .custom(matches: matches)
}
public func matches(_ header: RequestHeader) -> MatchedRoute? {
switch self {
case .path(let string) where normalizePath(header.path) == normalizePath(string):
return MatchedRoute()
case .path:
return nil
case .root where normalizePath(header.path) == normalizePath(""):
return MatchedRoute()
case .root:
return nil
case let .method(method, matcher) where method == header.method:
return matcher.matches(header)
case .method:
return nil
case let .interpolated(interpolatedPath):
return interpolatedPath.matches(header)
case let .multiple(matchers):
return matchers.lazy.compactMap({ $0.matches(header) }).first
case .any:
return MatchedRoute()
case .custom(let matches):
return matches(header)
}
}
public static func get(_ matcher: RouteMatcher) -> RouteMatcher {
self.method(.GET, matcher)
}
public static func post(_ matcher: RouteMatcher) -> RouteMatcher {
self.method(.POST, matcher)
}
public static func patch(_ matcher: RouteMatcher) -> RouteMatcher {
self.method(.PATCH, matcher)
}
public static func delete(_ matcher: RouteMatcher) -> RouteMatcher {
self.method(.DELETE, matcher)
}
}
extension RouteMatcher: ExpressibleByStringInterpolation {
public init(stringLiteral value: String) {
self = .path(value)
}
public init(stringInterpolation: InterpolatedPath) {
self = .interpolated(stringInterpolation)
}
}
extension RouteMatcher: ExpressibleByArrayLiteral {
public init(arrayLiteral elements: RouteMatcher...) {
self = .multiple(elements)
}
}
public struct InterpolatedPath: StringInterpolationProtocol, Sendable {
enum Component: Sendable {
case literal(String)
case parameter(name: String, type: LosslessStringConvertible.Type)
}
var components: [Component] = []
public init(literalCapacity: Int, interpolationCount: Int) {
}
mutating public func appendLiteral(_ literal: String) {
components.append(.literal(literal))
}
public mutating func appendInterpolation<SpecificKey: URLParameterKey>(_ urlParameter: KeyPath<ParameterKeys, SpecificKey>) {
components.append(.parameter(name: SpecificKey.stringKey, type: SpecificKey.DecodeType.self))
}
var regex: NSRegularExpression {
let regexString = components
.map({ component -> String in
switch component {
case .literal(let string):
return string
case .parameter:
return "([^/]+)"
}
})
.joined()
return try! NSRegularExpression(pattern: "^\(normalizePath(regexString))$")
}
var mapping: [(String, LosslessStringConvertible.Type)] {
components.compactMap({ component in
switch component {
case .literal(_):
nil
case .parameter(let name, let type):
(name, type)
}
})
}
var pathString: String {
components.compactMap({ component in
switch component {
case let .literal(string):
string
case .parameter(let name, _):
"{\(name.split(separator: ".").last ?? name[...])}"
}
})
.joined()
}
func matches(_ header: RequestHeader) -> MatchedRoute? {
let path = normalizePath(header.path)
let matches = regex.matches(in: path, range: NSRange(location: 0, length: path.utf16.count))
if matches.isEmpty {
return nil
}
var result: [String: Substring] = [:]
for match in matches {
let ranges = (0..<match.numberOfRanges)
.dropFirst() /*ignore the first match*/
.map({ match.range(at: $0) })
for (mapping, range) in zip(mapping, ranges) {
let (urlParameterName, type) = mapping
guard let nativeRange = Range(range, in: path) else { fatalError("Should be able to convert ranges") }
let substring = path[nativeRange]
let valueIsConvertible = type.init(String(substring)) != nil
guard valueIsConvertible else { return nil }
result[urlParameterName] = substring
}
}
return MatchedRoute(parameters: result)
}
}