Expand description
To support clients implementing the [Repository] trait in a ::wasm_bindgen environment,
we need to deal with an extern "C"
interface, as that is what ::wasm_bindgen supports:
This looks something like this:
β
#[wasm_bindgen]
extern "C" {
pub type CipherRepository;
#[wasm_bindgen(method, catch)]
async fn get(this: &CipherRepository, id: String) -> Result<JsValue, JsValue>;
}
As you can see, this has a few limitations:
- The type must be known at compile time, so we cannot use generics directly, which means we canβt use the existing [Repository] trait directly.
- The return type must be JsValue, so we need to convert our types to and from JsValue.
To facilitate this, we provide some utilities:
- WasmRepository trait, which defines the methods as we expect them to come from ::wasm_bindgen, using JsValue. This is generic and should be implemented for each concrete repository we define, but the implementation should be very straightforward.
- WasmRepositoryChannel struct, which wraps a WasmRepository in a [ThreadBoundRunner] and
implements the [Repository] trait. This has a few special considerations:
- It uses [tsify_next::serde_wasm_bindgen] to convert between JsValue and our types, so we can use the existing [Repository] trait.
- It runs the calls in a thread-bound manner, so we can safely call the WasmRepository methods from any thread.
- The create_wasm_repository macro, defines the ::wasm_bindgen interface and implements the WasmRepository trait for you.
MacrosΒ§
- create_
wasm_ πrepository - This macro generates a ::wasm_bindgen interface for a repository type, and provides the implementation of WasmRepository and a way to convert it into something that implements the [Repository] trait.
StructsΒ§
- Wasm
Repository πChannel - This struct wraps a WasmRepository in a [ThreadBoundRunner] to allow it to be used as a [Repository] in a thread-safe manner. It implements the [Repository] trait directly, by converting the values as needed with [tsify_next::serde_wasm_bindgen].
ConstantsΒ§
- UNIT π
TraitsΒ§
- Wasm
Repository π - This trait defines the methods that a ::wasm_bindgen repository must implement. The trait itself exists to provide a generic way of handling the ::wasm_bindgen interface, which is !Send + !Sync, and only deals with JsValue.
FunctionsΒ§
- convert_
result π - Converts a Result<JsValue, JsValue> to a typed Result<T, RepositoryError> using [tsify_next::serde_wasm_bindgen]
- run_
convert π - Utility function that runs a closure in a thread-bound manner, and converts the Result from Result<JsValue, JsValue> to a typed Result<T, RepositoryError>.