-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathURLTransformer.swift
More file actions
49 lines (42 loc) · 1.67 KB
/
URLTransformer.swift
File metadata and controls
49 lines (42 loc) · 1.67 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
//
// URLTransformer.swift
// QuickHatchHTTP
//
// Created by Daniel Koster on 8/29/25.
//
import Foundation
public protocol URLTransformer {
func transform(url: String, parameters: [String: any Sendable]) -> String
}
public struct DefaultURLTransformer: URLTransformer {
private let parameterTransformer: ParameterTransformer
public init(parameterTransformer: ParameterTransformer) {
self.parameterTransformer = parameterTransformer
}
public func transform(url: String, parameters: [String : any Sendable]) -> String {
if url.isEmpty { return "" }
let params = parameterTransformer.transform(parameters: parameters)
return params.isEmpty ? url : url + "?" + params
}
}
/// MARK: Use this transformer for parameter mapping
/// Example: Input -> https://quickhatch.com/{user_id}|/{age}
///
/// Example: ParameterMappingURLTransformer().transform("https://quickhatch.com/{user_id}|/{age}", ["user_id": "ABCD1234", "age": 20])
///
/// Example: Output -> https://quickhatch.com/ABCD1234/20
///
public struct ParameterMappingURLTransformer: URLTransformer {
public init() {}
public func transform(url: String, parameters: [String : any Sendable]) -> String {
guard !url.isEmpty else { return url }
let parameters = parameters.flatMap { (key, value) in EncodingHelpers.queryComponents(fromKey: key, value: value) }
guard !parameters.isEmpty else { return url }
var urlResult = url
for (key, value) in parameters {
let escapedKey = "{\(key)}"
urlResult = urlResult.replacingOccurrences(of: escapedKey, with: value)
}
return urlResult
}
}