From 1312b4cb920ff763a8b39e0865b55665375ee2eb Mon Sep 17 00:00:00 2001
From: Dariusz Rybicki <dariusz@elixxir.io>
Date: Tue, 26 Jul 2022 13:39:42 +0100
Subject: [PATCH] Add RestlikeCallback wrapper

---
 .../ElixxirDAppsSDK/RestlikeCallback.swift    | 44 +++++++++++++++++++
 1 file changed, 44 insertions(+)
 create mode 100644 Sources/ElixxirDAppsSDK/RestlikeCallback.swift

diff --git a/Sources/ElixxirDAppsSDK/RestlikeCallback.swift b/Sources/ElixxirDAppsSDK/RestlikeCallback.swift
new file mode 100644
index 00000000..1facd9d0
--- /dev/null
+++ b/Sources/ElixxirDAppsSDK/RestlikeCallback.swift
@@ -0,0 +1,44 @@
+import Bindings
+import XCTestDynamicOverlay
+
+public struct RestlikeCallback {
+  public init(handle: @escaping (Result<RestlikeMessage, NSError>) -> Void) {
+    self.handle = handle
+  }
+
+  public var handle: (Result<RestlikeMessage, NSError>) -> Void
+}
+
+extension RestlikeCallback {
+  public static let unimplemented = RestlikeCallback(
+    handle: XCTUnimplemented("\(Self.self)")
+  )
+}
+
+extension RestlikeCallback {
+  func makeBindingsRestlikeCallback() -> BindingsRestlikeCallbackProtocol {
+    class Callback: NSObject, BindingsRestlikeCallbackProtocol {
+      init(_ callback: RestlikeCallback) {
+        self.callback = callback
+      }
+
+      let callback: RestlikeCallback
+
+      func callback(_ p0: Data?, p1: Error?) {
+        if let error = p1 {
+          callback.handle(.failure(error as NSError))
+        } else if let messageData = p0 {
+          do {
+            callback.handle(.success(try RestlikeMessage.decode(messageData)))
+          } catch {
+            callback.handle(.failure(error as NSError))
+          }
+        } else {
+          fatalError("BindingsRestlikeCallback received `nil` message and `nil` error")
+        }
+      }
+    }
+
+    return Callback(self)
+  }
+}
-- 
GitLab