-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Extend date decoding strategy for possible fractional seconds (#35)
* Add support for fractional seconds in dates If the WriteFreely instance returns dates with fractional seconds (e.g., 2022-09-28T11:55:39.886581893Z), the date-decoding strategy fails and an error is thrown. * Switch formatOptions depending on fractional seconds * Bump minimum OS versions
- Loading branch information
1 parent
f700e05
commit 0361ed3
Showing
3 changed files
with
36 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
33 changes: 33 additions & 0 deletions
33
Sources/WriteFreely/Extensions/JSONDecoder+Extension.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
// Credit: https://github.com/vapor/vapor/issues/2481#issuecomment-702013846 | ||
|
||
import Foundation | ||
|
||
extension JSONDecoder.DateDecodingStrategy { | ||
|
||
/// The strategy that formats dates according to the ISO 8601 standard. | ||
/// - Note: This includes the fractional seconds, unlike the standard `.iso8601`, which fails to decode those. | ||
static var iso8601WithPossibleFractionalSeconds: JSONDecoder.DateDecodingStrategy { | ||
JSONDecoder.DateDecodingStrategy.custom { (decoder) in | ||
let singleValue = try decoder.singleValueContainer() | ||
let dateString = try singleValue.decode(String.self) | ||
|
||
let formatter = ISO8601DateFormatter() | ||
|
||
/// Use the `.withFractionalSeconds` option only if we have fractional seconds in the date string. | ||
if dateString.contains(".") { | ||
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds] | ||
} else { | ||
formatter.formatOptions = [.withInternetDateTime] | ||
} | ||
|
||
guard let date = formatter.date(from: dateString) else { | ||
throw DecodingError.dataCorruptedError( | ||
in: singleValue, | ||
debugDescription: "Failed to decode string to ISO 8601 date." | ||
) | ||
} | ||
return date | ||
} | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters