Skip to content

Commit 10d6b7e

Browse files
committed
set .dateDecodingStrategy
1 parent 586cdfd commit 10d6b7e

3 files changed

Lines changed: 48 additions & 1 deletion

File tree

Sources/TwitterAPIKit/Extensions/Concurrency.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ extension TwitterAPISessionJSONTask {
4545
}
4646
}
4747

48-
public func responseDecodable<T: Decodable>(type: T.Type) async -> TwitterAPIResponse<T> {
48+
public func responseDecodable<T: Decodable>(type: T.Type, decoder: JSONDecoder = TwitterAPIClient.defaultJSONDecoder) async -> TwitterAPIResponse<T> {
4949
return await withTaskCancellationHandler(
5050
operation: {
5151
return await withCheckedContinuation { c in

Sources/TwitterAPIKit/TwitterAPIClient.swift

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,32 @@ open class TwitterAPIClient {
55
public static var defaultJSONDecoder: JSONDecoder = {
66
let decoder = JSONDecoder()
77
decoder.keyDecodingStrategy = .convertFromSnakeCase
8+
9+
// for v1
10+
let dateFormatterV1 = DateFormatter()
11+
dateFormatterV1.locale = Locale(identifier: "en_US_POSIX")
12+
dateFormatterV1.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
13+
14+
// for v2
15+
let dateFormatterV2 = DateFormatter()
16+
dateFormatterV2.locale = Locale(identifier: "en_US_POSIX")
17+
dateFormatterV2.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
18+
19+
decoder.dateDecodingStrategy = .custom { decoder -> Date in
20+
let container = try decoder.singleValueContainer()
21+
let dateStr = try container.decode(String.self)
22+
23+
if let date = dateFormatterV1.date(from: dateStr) {
24+
return date
25+
}
26+
27+
if let date = dateFormatterV2.date(from: dateStr) {
28+
return date
29+
}
30+
throw DecodingError.dataCorrupted(
31+
.init(codingPath: decoder.codingPath, debugDescription: "Unexpected date format: \(dateStr)"))
32+
}
33+
834
return decoder
935
}()
1036

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import TwitterAPIKit
2+
import XCTest
3+
4+
class TwitterAPIClientTests: XCTestCase {
5+
6+
override func setUpWithError() throws {
7+
}
8+
9+
override func tearDownWithError() throws {
10+
}
11+
12+
func testJSONDecoder() throws {
13+
14+
let decoder = TwitterAPIClient.defaultJSONDecoder
15+
16+
let dateV1 = try decoder.decode(Date.self, from: Data("\"Sun Jul 03 04:32:05 +0000 2022\"".utf8))
17+
let dateV2 = try decoder.decode(Date.self, from: Data("\"2022-07-03T04:32:05.000Z\"".utf8))
18+
XCTAssertEqual(dateV1, dateV2)
19+
}
20+
21+
}

0 commit comments

Comments
 (0)