Skip to content

Commit

Permalink
Add from_string and to_cbor methods
Browse files Browse the repository at this point in the history
  • Loading branch information
kearfy committed Apr 24, 2024
1 parent d81c38f commit 334efef
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { SurrealQL, Value } from 'https://unpkg.com/surrealql.wasm/lib/v2.js';
import { SurrealQL, Value } from 'surrealql.wasm/v1';

// Creating a SurrealQL Value
const value = Value.from_string("{ id: \"person:tobie\" }");
const value = Value.from_json({ id: "person:tobie" });
const value = Value.from_cbor(/* Uint8Array */);

Expand All @@ -36,6 +37,8 @@ value.format(true); // Pretty
value.json();
value.json(true); // Pretty

// Converting a value to CBOR, represented as a Uint8Array
value.to_cbor();

// Parsing queries
SurrealQL.parse("SELECT * FROM person");
Expand Down
28 changes: 28 additions & 0 deletions src/app/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use serde_json::ser::PrettyFormatter;
use serde_json::Value as Json;
use serde_wasm_bindgen::from_value;
use surrealdb::rpc::format::cbor::Cbor;
use surrealdb::sql::json;
use wasm_bindgen::prelude::JsValue;
use wasm_bindgen::prelude::*;
use web_sys::js_sys::Uint8Array;
Expand Down Expand Up @@ -73,6 +74,17 @@ pub struct Value {

#[wasm_bindgen]
impl Value {
/// Create a new SurrealQL value
///
/// ```js
/// const value = Value.from_string("{ test: true }");
/// ```
#[wasm_bindgen]
pub fn from_string(val: String) -> Result<Value, Error> {
let val = json(&val).map_err(|_| "Failed to parse value from string")?;
Ok(Value { inner: val })
}

/// Create a new SurrealQL value
///
/// ```js
Expand Down Expand Up @@ -135,4 +147,20 @@ impl Value {
false => self.inner.clone().into_json().to_string(),
})
}

/// Return a parsed SurrealQL value as CBOR
///
/// ```js
/// const value = Value.from_string("{ test: true }");
/// const output = value.to_cbor();
///
#[wasm_bindgen]
pub fn to_cbor(&self) -> Result<Uint8Array, Error> {
// Into CBOR value
let cbor: Cbor = self.inner.clone().try_into().map_err(|_| "Failed to convert Value to CBOR")?;
let mut res = Vec::new();
ciborium::into_writer(&cbor.0, &mut res).unwrap();
let out_arr: Uint8Array = res.as_slice().into();
Ok(out_arr.into())
}
}

0 comments on commit 334efef

Please sign in to comment.