I really appreciate it, thanks for this!
Currently, I’m in the process of utilising URL.Template in a network client lib (yeah, yet another one). So far, I can really appreciate the current work.
However, I’m missing one feature: URL Template composition
Much like composing a URI from a given URI-Reference and a given base URI (see RFC 3986), we could imagine to provide the same functionality for URL.Templates.
I would appreciate it, if this could be implemented ;) - even though, there's no RFC for this.
This feature would make sense in the library I’m currently developing. It’s kind of a DSL to define endpoints:
Endpoint declaration:
// 1. Session with template variable in base URL
enum MultiTenantAPI: Session {
static let baseURL = "https://{tenant}.api.example.com" // a BaseURLTemplateString
}
// 2. Group with template variable in path
enum APIVersion: Group {
typealias Base = MultiTenantAPI
static let path = "api/{version}" // a ReferenceURLTemplateString
// Composed result: URL.Template("https://{tenant}.api.example.com/api/{version}")
}
// 3. The hypothetical composeURL that would enable this:
func composeURL(
urlReference: ReferenceURLTemplateString, // "/api/{version}"
relativeTo baseURL: URL.Template? // URL.Template("https://{tenant}.api.example.com")
) -> URL.Template // URL.Template("https://{tenant}.api.example.com/api/{version}")
An endpoint might then be declared like this:
enum GetUser: Endpoint {
typealias Session = UsersGroup
static let path = "{userId}"
// Final template: https://{tenant}.api.example.com/api/{version}/users/{userId}
typealias Output = User
struct URLParams: Encodable {
let tenant: String // From base Session
let version: String // From Group
let userId: String // From Endpoint
}
}
I guess, you get the point.
Without going into details, how the library works exactly, in addition to make this work, the library has a URLTemplateVariablesEncoder - which encodes types conforming to Encodable into a URL.Template variables dictionary.
This encoder basically is akin to a JSONDecoder, i.e. with strategies to encode keys and values. This is the "missing component" to make URL.Template universally usable in applications ;)
Now, the missing feature in URL.Template would be composition, much like specified in RFC 3986 for regular URIs.
What do you think?