//
//  JSONCoderExtension.swift
//  Nextcloud Cookbook iOS Client
//
//  Created by Vincent Meilinger on 20.09.23.
//

import Foundation
import OSLog

extension JSONDecoder {
    static func safeDecode<T: Decodable>(_ data: Data) -> T? {
        let decoder = JSONDecoder()
        do {
            return try decoder.decode(T.self, from: data)
        } catch {
            Logger.data.error("JSONDecoder - safeDecode(): \(error.localizedDescription)")
            return nil
        }
    }
}

extension JSONEncoder {
    static func safeEncode<T: Encodable>(_ object: T) -> Data? {
        do {
            return try JSONEncoder().encode(object)
        } catch {
            Logger.data.error("JSONEncoder - safeEncode(): Could not encode \(String(describing: T.self))")
        }
        return nil
    }
}
