Skip to content

Commit 69a7588

Browse files
committed
Improve how nils is handled
1 parent be8c8e0 commit 69a7588

File tree

2 files changed

+33
-10
lines changed

2 files changed

+33
-10
lines changed

Sources/URLQueryEncoder/URLQueryEncoder.swift

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -73,14 +73,6 @@ public class URLQueryEncoder {
7373
try? value.encode(to: self)
7474
}
7575

76-
#warning("do we need this method?")
77-
public func encode<V: Encodable>(_ value: V, forKey key: String, explode: Bool? = nil, delimeter: String? = nil, isDeepObject: Bool? = nil) {
78-
_explode = explode ?? self.explode
79-
_delimeter = delimeter ?? self.delimeter
80-
_isDeepObject = isDeepObject ?? self.isDeepObject
81-
try? [key: value].encode(to: self)
82-
}
83-
8476
public static func data(for queryItems: [URLQueryItem]) -> Data {
8577
var components = URLComponents()
8678
components.queryItems = queryItems
@@ -89,9 +81,8 @@ public class URLQueryEncoder {
8981
}
9082

9183
private extension URLQueryEncoder {
92-
#warning("test encodeNil extensively!")
9384
func encodeNil(forKey codingPath: [CodingKey]) throws {
94-
queryItems.append(URLQueryItem(name: codingPath.last?.stringValue ?? "", value: nil))
85+
// Do nothing
9586
}
9687

9788
func encode(_ value: String, forKey codingPath: [CodingKey]) throws {

Tests/URLQueryEncoderTests/URLQueryEncoderTests.swift

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,38 @@ final class QueryEncoderTests: XCTestCase {
204204
XCTAssertEqual(encoder.query, "id[role]=admin&id[name]=kean")
205205
XCTAssertEqual(encoder.percentEncodedQuery, "id%5Brole%5D=admin&id%5Bname%5D=kean")
206206
}
207+
208+
// MARK: Misc
209+
210+
func testMixingDifferentStyles() {
211+
// GIVEN
212+
let user = User(role: "admin", name: "kean")
213+
let ids = [3, 4, 5]
214+
215+
// WHEN
216+
let encoder = URLQueryEncoder()
217+
encoder.encode(["ids": ids], explode: false)
218+
encoder.encode(["ids2": ids], explode: true)
219+
encoder.encode(["user": user], isDeepObject: true)
220+
encoder.encode(["id": 2])
221+
222+
// THEN
223+
XCTAssertEqual(encoder.query, "ids=3,4,5&ids2=3&ids2=4&ids2=5&user[role]=admin&user[name]=kean&id=2")
224+
}
225+
226+
// MARK: Encoding Nils
227+
228+
func testEncodingNil() {
229+
// GIVEN
230+
let id: Int? = nil
231+
232+
// THEN
233+
let encoder = URLQueryEncoder()
234+
encoder.encode(["id": id])
235+
236+
// THEN
237+
XCTAssertTrue(encoder.queryItems.isEmpty)
238+
}
207239
}
208240

209241
private struct User: Encodable {

0 commit comments

Comments
 (0)