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