Channel.swift 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. import Foundation
  5. let CHANNEL_PREFIX = "__CHANNEL__:"
  6. let channelDataKey = CodingUserInfoKey(rawValue: "sendChannelData")!
  7. public class Channel: Decodable {
  8. public let id: UInt64
  9. let handler: (UInt64, String) -> Void
  10. public required init(from decoder: Decoder) throws {
  11. let container = try decoder.singleValueContainer()
  12. let channelDef = try container.decode(String.self)
  13. let components = channelDef.components(separatedBy: CHANNEL_PREFIX)
  14. if components.count < 2 {
  15. throw DecodingError.dataCorruptedError(
  16. in: container,
  17. debugDescription: "Invalid channel definition from \(channelDef)"
  18. )
  19. }
  20. guard let channelId = UInt64(components[1]) else {
  21. throw DecodingError.dataCorruptedError(
  22. in: container,
  23. debugDescription: "Invalid channel ID from \(channelDef)"
  24. )
  25. }
  26. guard let handler = decoder.userInfo[channelDataKey] as? (UInt64, String) -> Void else {
  27. throw DecodingError.dataCorruptedError(
  28. in: container,
  29. debugDescription: "missing userInfo for Channel handler. This is a Tauri issue"
  30. )
  31. }
  32. self.id = channelId
  33. self.handler = handler
  34. }
  35. func serialize(_ data: JsonValue) -> String {
  36. do {
  37. return try data.jsonRepresentation() ?? "\"Failed to serialize payload\""
  38. } catch {
  39. return "\"\(error)\""
  40. }
  41. }
  42. public func send(_ data: JsonObject) {
  43. send(.dictionary(data))
  44. }
  45. public func send(_ data: JsonValue) {
  46. handler(id, serialize(data))
  47. }
  48. public func send<T: Encodable>(_ data: T) throws {
  49. let json = try JSONEncoder().encode(data)
  50. handler(id, String(decoding: json, as: UTF8.self))
  51. }
  52. }