2020-07-29 23:50:30 +00:00
|
|
|
// Copyright © 2020 Metabolist. All rights reserved.
|
|
|
|
|
|
|
|
import Foundation
|
|
|
|
|
2020-09-04 01:55:46 +00:00
|
|
|
public final class MastodonDecoder: JSONDecoder {
|
2020-08-30 23:33:11 +00:00
|
|
|
public override init() {
|
2020-07-29 23:50:30 +00:00
|
|
|
super.init()
|
|
|
|
|
|
|
|
keyDecodingStrategy = .convertFromSnakeCase
|
2021-03-13 02:27:07 +00:00
|
|
|
dateDecodingStrategy = .custom { decoder in
|
|
|
|
let container = try decoder.singleValueContainer()
|
|
|
|
let dateString = try container.decode(String.self)
|
|
|
|
|
2021-05-08 21:41:55 +00:00
|
|
|
guard let date = Self.dateFormatter.date(from: dateString)
|
|
|
|
?? Self.dateFormatterWithoutFractionalSeconds.date(from: dateString) else {
|
2021-03-13 02:27:07 +00:00
|
|
|
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Unable to parse ISO8601 date")
|
|
|
|
}
|
|
|
|
|
|
|
|
return date
|
|
|
|
}
|
2020-07-29 23:50:30 +00:00
|
|
|
}
|
|
|
|
}
|
2021-03-13 02:27:07 +00:00
|
|
|
|
|
|
|
public extension MastodonDecoder {
|
|
|
|
static let dateFormatter: ISO8601DateFormatter = {
|
|
|
|
let dateFormatter = ISO8601DateFormatter()
|
|
|
|
|
|
|
|
dateFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
|
|
|
|
|
|
|
|
return dateFormatter
|
|
|
|
}()
|
2021-05-08 21:41:55 +00:00
|
|
|
|
|
|
|
static let dateFormatterWithoutFractionalSeconds: ISO8601DateFormatter = {
|
|
|
|
let dateFormatter = ISO8601DateFormatter()
|
|
|
|
|
|
|
|
dateFormatter.formatOptions = [.withInternetDateTime]
|
|
|
|
|
|
|
|
return dateFormatter
|
|
|
|
}()
|
2021-03-13 02:27:07 +00:00
|
|
|
}
|