|
1 | 1 | import HTTPTypes |
2 | 2 |
|
3 | | -package extension HTTPFields { |
4 | | - init(_ dictionary: [String: String]) { |
| 3 | +extension HTTPFields { |
| 4 | + package init(_ dictionary: [String: String]) { |
5 | 5 | self.init(dictionary.map { .init(name: .init($0.key)!, value: $0.value) }) |
6 | 6 | } |
7 | | - |
8 | | - var dictionary: [String: String] { |
| 7 | + |
| 8 | + package var dictionary: [String: String] { |
9 | 9 | let keyValues = self.map { |
10 | 10 | ($0.name.rawName, $0.value) |
11 | 11 | } |
12 | | - |
| 12 | + |
13 | 13 | return .init(keyValues, uniquingKeysWith: { $1 }) |
14 | 14 | } |
15 | | - |
16 | | - mutating func merge(with other: Self) { |
| 15 | + |
| 16 | + package mutating func merge(with other: Self) { |
17 | 17 | for field in other { |
18 | 18 | self[field.name] = field.value |
19 | 19 | } |
20 | 20 | } |
21 | | - |
22 | | - func merging(with other: Self) -> Self { |
| 21 | + |
| 22 | + package func merging(with other: Self) -> Self { |
23 | 23 | var copy = self |
24 | | - |
| 24 | + |
25 | 25 | for field in other { |
26 | 26 | copy[field.name] = field.value |
27 | 27 | } |
28 | 28 |
|
29 | 29 | return copy |
30 | 30 | } |
| 31 | + |
| 32 | + /// Append or update a value in header. |
| 33 | + /// |
| 34 | + /// Example: |
| 35 | + /// ```swift |
| 36 | + /// var headers: HTTPFields = [ |
| 37 | + /// "Prefer": "count=exact,return=representation" |
| 38 | + /// ] |
| 39 | + /// |
| 40 | + /// headers.appendOrUpdate(.prefer, value: "return=minimal") |
| 41 | + /// #expect(headers == ["Prefer": "count=exact,return=minimal"] |
| 42 | + /// ``` |
| 43 | + package mutating func appendOrUpdate( |
| 44 | + _ name: HTTPField.Name, |
| 45 | + value: String, |
| 46 | + separator: String = "," |
| 47 | + ) { |
| 48 | + if let currentValue = self[name] { |
| 49 | + var components = currentValue.components(separatedBy: separator) |
| 50 | + |
| 51 | + if let key = value.split(separator: "=").first, |
| 52 | + let index = components.firstIndex(where: { $0.hasPrefix("\(key)=") }) |
| 53 | + { |
| 54 | + components[index] = value |
| 55 | + } else { |
| 56 | + components.append(value) |
| 57 | + } |
| 58 | + |
| 59 | + self[name] = components.joined(separator: separator) |
| 60 | + } else { |
| 61 | + self[name] = value |
| 62 | + } |
| 63 | + } |
31 | 64 | } |
32 | 65 |
|
33 | | -package extension HTTPField.Name { |
34 | | - static let xClientInfo = HTTPField.Name("X-Client-Info")! |
35 | | - static let xRegion = HTTPField.Name("x-region")! |
36 | | - static let xRelayError = HTTPField.Name("x-relay-error")! |
| 66 | +extension HTTPField.Name { |
| 67 | + package static let xClientInfo = HTTPField.Name("X-Client-Info")! |
| 68 | + package static let xRegion = HTTPField.Name("x-region")! |
| 69 | + package static let xRelayError = HTTPField.Name("x-relay-error")! |
37 | 70 | } |
0 commit comments