|
| 1 | +use napi::threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode}; |
1 | 2 | use napi_derive::napi; |
2 | 3 |
|
3 | 4 | use crate::prelude::{ |
| 5 | + CodempAsyncReceiver as AsyncReceiver, |
4 | 6 | CodempConfig as Config, |
5 | 7 | CodempClient as Client, |
6 | 8 | CodempUserInfo as UserInfo, |
| 9 | + CodempSessionEvent as SessionEvent, |
7 | 10 | CodempWorkspace as Workspace, |
8 | 11 | CodempWorkspaceIdentifier as WorkspaceIdentifier, |
9 | 12 | }; |
@@ -111,5 +114,46 @@ impl Client { |
111 | 114 | Ok(self.reject_invite(&user, &workspace).await?) |
112 | 115 | } |
113 | 116 |
|
| 117 | + /// Register a callback to be called on receive. |
| 118 | + /// There can only be one callback registered at any given time. |
| 119 | + #[napi( |
| 120 | + js_name = "callback", |
| 121 | + ts_args_type = "fun: (err: Error|null, event: Client) => void" |
| 122 | + )] |
| 123 | + pub fn js_callback( |
| 124 | + &self, |
| 125 | + fun: ThreadsafeFunction<Client>, |
| 126 | + ) -> napi::Result<()> { |
| 127 | + self.callback(move |controller: Client| { |
| 128 | + fun.call(Ok(controller.clone()), ThreadsafeFunctionCallMode::Blocking); |
| 129 | + //check this with tracing also we could use Ok(event) to get the error |
| 130 | + // If it blocks the main thread too many time we have to change this |
| 131 | + }); |
| 132 | + |
| 133 | + Ok(()) |
| 134 | + } |
| 135 | + |
| 136 | + /// Clear the registered callback |
| 137 | + #[napi(js_name = "clearCallback")] |
| 138 | + pub fn js_clear_callback(&self) { |
| 139 | + self.clear_callback(); |
| 140 | + } |
114 | 141 |
|
| 142 | + /// Get next session event if available without blocking |
| 143 | + #[napi(js_name = "tryRecv")] |
| 144 | + pub async fn js_try_recv(&self) -> napi::Result<Option<SessionEvent>> { |
| 145 | + Ok(self.try_recv().await?) |
| 146 | + } |
| 147 | + |
| 148 | + /// Block until next session event |
| 149 | + #[napi(js_name = "recv")] |
| 150 | + pub async fn js_recv(&self) -> napi::Result<SessionEvent> { |
| 151 | + Ok(self.recv().await?) |
| 152 | + } |
| 153 | + |
| 154 | + /// Block until next session event without returning it |
| 155 | + #[napi(js_name = "poll")] |
| 156 | + pub async fn js_poll(&self) -> napi::Result<()> { |
| 157 | + Ok(self.poll().await?) |
| 158 | + } |
115 | 159 | } |
0 commit comments