From 7865e89b663e31612278ea1d0a5727f81333aebc Mon Sep 17 00:00:00 2001 From: Kevin Hermawan <84965338+kevinhermawan@users.noreply.github.com> Date: Wed, 15 Nov 2023 03:08:37 +0700 Subject: [PATCH] refactor: implements a custom date decoding strategy --- .../Extensions/JSONDecoder+Default.swift | 25 ++++++++++++++----- 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/Sources/OllamaKit/Extensions/JSONDecoder+Default.swift b/Sources/OllamaKit/Extensions/JSONDecoder+Default.swift index 97a1b55..56cc665 100644 --- a/Sources/OllamaKit/Extensions/JSONDecoder+Default.swift +++ b/Sources/OllamaKit/Extensions/JSONDecoder+Default.swift @@ -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 }