Skip to content
This repository has been archived by the owner on Aug 12, 2022. It is now read-only.

Use R2Shared's URITemplate to expand Link's href #93

Merged
merged 2 commits into from
Oct 19, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 5 additions & 14 deletions readium-lcp-swift/License/Model/Components/Link.swift
Original file line number Diff line number Diff line change
Expand Up @@ -56,23 +56,14 @@ public struct Link {

/// Gets the valid URL if possible, applying the given template context as query parameters if the link is templated.
/// eg. http://url{?id,name} + [id: x, name: y] -> http://url?id=x&name=y
func url(with parameters: [String: CustomStringConvertible]) -> URL? {
if !templated {
return URL(string: href)
}

let urlString = href.replacingOccurrences(of: "\\{\\?.+?\\}", with: "", options: [.regularExpression])

guard var urlBuilder = URLComponents(string: urlString) else {
return nil
}
func url(with parameters: [String: LosslessStringConvertible]) -> URL? {
var href = self.href

// Add the template context as query parameters
urlBuilder.queryItems = parameters.map { param in
URLQueryItem(name: param.key, value: param.value.description)
if templated {
href = URITemplate(href).expand(with: parameters.mapValues { String(describing: $0) })
}

return urlBuilder.url
return URL(string: href)
}

/// Expands the href without any template context.
Expand Down
2 changes: 1 addition & 1 deletion readium-lcp-swift/License/Model/LicenseDocument.swift
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ public struct LicenseDocument {

/// Gets and expands the URL for the given rel, if it exits.
/// - Throws: `LCPError.invalidLink` if the URL can't be built.
func url(for rel: Rel, with parameters: [String: CustomStringConvertible] = [:]) throws -> URL {
func url(for rel: Rel, with parameters: [String: LosslessStringConvertible] = [:]) throws -> URL {
guard let url = link(for: rel)?.url(with: parameters) else {
throw ParsingError.url(rel: rel.rawValue)
}
Expand Down
2 changes: 1 addition & 1 deletion readium-lcp-swift/License/Model/StatusDocument.swift
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ public struct StatusDocument {

/// Gets and expands the URL for the given rel, if it exits.
/// - Throws: `LCPError.invalidLink` if the URL can't be built.
func url(for rel: Rel, with parameters: [String: CustomStringConvertible] = [:]) throws -> URL {
func url(for rel: Rel, with parameters: [String: LosslessStringConvertible] = [:]) throws -> URL {
guard let url = link(for: rel)?.url(with: parameters) else {
throw ParsingError.url(rel: rel.rawValue)
}
Expand Down