import Foundation

@propertyWrapper
struct Nullable<T>: Encodable where T: Encodable {
  var wrappedValue: T?

  init(wrappedValue: T?) {
    self.wrappedValue = wrappedValue
  }

  func encode(to encoder: Encoder) throws {
    var container = encoder.singleValueContainer()

    switch wrappedValue {
    case .some(let value): try container.encode(value)
    case .none: try container.encodeNil()
    }
  }
}

func encoder(_ data: Encodable) -> [String: Any]? {
  do {
    let encoder = JSONEncoder()
    let jsonData = try encoder.encode(data)

    guard let dictionary = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] else {
      return nil
    }

    return dictionary
  } catch {
    return nil
  }
}
