Skip to content

Commit

Permalink
Merge pull request #273 from mattpolzin/bugfix/2x/path-trailing-slash
Browse files Browse the repository at this point in the history
support trailing slashes in paths (which are sometimes required by APIs)
  • Loading branch information
mattpolzin authored Jun 13, 2023
2 parents d3c27d8 + b5f5c3a commit 70b9c43
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
12 changes: 10 additions & 2 deletions Sources/OpenAPIKit/Path Item/PathItem.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,28 @@ extension OpenAPI {
/// and [OpenAPI Patterned Fields](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#patterned-fields).
public struct Path: RawRepresentable, Equatable, Hashable {
public let components: [String]
public let trailingSlash: Bool

public init(_ components: [String]) {
public init(_ components: [String], trailingSlash: Bool = false) {
self.components = components
self.trailingSlash = trailingSlash
}

public init(rawValue: String) {
let pathComponents = rawValue.split(separator: "/").map(String.init)
components = pathComponents.count > 0 && pathComponents[0].isEmpty
? Array(pathComponents.dropFirst())
: pathComponents
trailingSlash = rawValue.hasSuffix("/")
}

public var rawValue: String {
return "/\(components.joined(separator: "/"))"
let path =
"/\(components.joined(separator: "/"))"

let suffix = trailingSlash ? "/" : ""

return path + suffix
}
}
}
Expand Down
5 changes: 5 additions & 0 deletions Tests/OpenAPIKitTests/Path Item/PathItemTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,22 @@ final class PathItemTests: XCTestCase {
let t3 = OpenAPI.Path(rawValue: "hello/world")
let t4: OpenAPI.Path = "/hello/world"
let t5: OpenAPI.Path = "hello/world"
let t6: OpenAPI.Path = "hello/world/"
let t7 = OpenAPI.Path(["hello", "world"], trailingSlash: true)

XCTAssertEqual(t1, t2)
XCTAssertEqual(t2, t3)
XCTAssertEqual(t3, t4)
XCTAssertEqual(t4, t5)
XCTAssertNotEqual(t5,t6)
XCTAssertEqual(t6, t7)

XCTAssertEqual(t1.rawValue, "/hello/world")
XCTAssertEqual(t2.rawValue, "/hello/world")
XCTAssertEqual(t3.rawValue, "/hello/world")
XCTAssertEqual(t4.rawValue, "/hello/world")
XCTAssertEqual(t5.rawValue, "/hello/world")
XCTAssertEqual(t6.rawValue, "/hello/world/")
}

func test_initializePathItem() {
Expand Down

0 comments on commit 70b9c43

Please sign in to comment.