Skip to content

Commit

Permalink
refactor: implements a custom date decoding strategy
Browse files Browse the repository at this point in the history
  • Loading branch information
kevinhermawan committed Nov 14, 2023
1 parent 99ec232 commit 7865e89
Showing 1 changed file with 19 additions and 6 deletions.
25 changes: 19 additions & 6 deletions Sources/OllamaKit/Extensions/JSONDecoder+Default.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,27 @@ import Foundation

internal extension JSONDecoder {
static var `default`: JSONDecoder {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSSZZZZZ"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(dateFormatter)
decoder.keyDecodingStrategy = .convertFromSnakeCase
decoder.dateDecodingStrategy = .custom { decoder -> Date in
let container = try decoder.singleValueContainer()
let dateString = try container.decode(String.self)

let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]

if let date = formatter.date(from: dateString) {
return date
}

formatter.formatOptions = [.withInternetDateTime]

if let date = formatter.date(from: dateString) {
return date
}

throw DecodingError.dataCorruptedError(in: container, debugDescription: "Cannot decode date string \(dateString)")
}

return decoder
}
Expand Down

0 comments on commit 7865e89

Please sign in to comment.