Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 9 additions & 11 deletions crates/neon/src/types_impl/extract/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use crate::{
result::{JsResult, NeonResult},
types::{
extract::{private, TryFromJs, TryIntoJs},
JsError, JsFunction, JsObject, JsString, JsValue,
JsError, JsFunction, JsObject, JsValue,
},
};

Expand Down Expand Up @@ -52,13 +52,6 @@ fn json_stringify<'cx>(cx: &mut Cx<'cx>) -> JsResult<'cx, JsFunction> {
.map(|f| f.to_inner(cx))
}

fn stringify(cx: &mut Cx, v: Handle<JsValue>) -> NeonResult<String> {
json_stringify(cx)?
.call(cx, v, [v])?
.downcast_or_throw::<JsString, _>(cx)
.map(|s| s.value(cx))
}

fn global_json_parse<'cx>(cx: &mut Cx<'cx>) -> JsResult<'cx, JsFunction> {
cx.global::<JsObject>("JSON")?.get(cx, "parse")
}
Expand Down Expand Up @@ -97,9 +90,14 @@ where
cx: &mut Cx<'cx>,
v: Handle<'cx, JsValue>,
) -> NeonResult<Result<Self, Self::Error>> {
Ok(serde_json::from_str(&stringify(cx, v)?)
.map(Json)
.map_err(Error))
let s = json_stringify(cx)?.call(cx, v, [v])?;
let res = match String::try_from_js(cx, s)? {
Comment thread
kjvalencik marked this conversation as resolved.
Ok(s) => serde_json::from_str(&s),
// If the type was not a `string`, it must be `undefined`
Comment thread
kjvalencik marked this conversation as resolved.
Err(_) => T::deserialize(serde::de::value::UnitDeserializer::new()),
};

Ok(res.map(Json).map_err(Error))
}
}

Expand Down
3 changes: 3 additions & 0 deletions test/napi/lib/extract.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,9 @@ describe("Extractors", () => {
it("JSON", () => {
assert.strictEqual(addon.extract_json_sum([1, 2, 3, 4]), 10);
assert.strictEqual(addon.extract_json_sum([8, 16, 18]), 42);
assert.strictEqual(addon.extractJsonOption(42), 42);
assert.strictEqual(addon.extractJsonOption(null), null);
assert.strictEqual(addon.extractJsonOption(), null);
});

it("Either", () => {
Expand Down
5 changes: 5 additions & 0 deletions test/napi/src/js/extract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,11 @@ pub fn extract_single_add_one(mut cx: FunctionContext) -> JsResult<JsNumber> {
Ok(cx.number(n + 1.0))
}

#[neon::export(json)]
Comment thread
kjvalencik marked this conversation as resolved.
pub fn extract_json_option(maybe_x: Option<f64>) -> Option<f64> {
maybe_x
}

#[neon::export]
pub fn extract_either(either: Either<String, f64>) -> String {
match either {
Expand Down