Skip to content

Commit

Permalink
Add Object::get_opt and Object::get_value convenience APIs.
Browse files Browse the repository at this point in the history
  • Loading branch information
dherman committed Mar 4, 2022
1 parent 6e2a379 commit 06d95ea
Showing 1 changed file with 26 additions and 5 deletions.
31 changes: 26 additions & 5 deletions src/object/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ mod traits {
use crate::handle::{Handle, Managed, Root};
use crate::result::{NeonResult, Throw};
use crate::types::utf8::Utf8;
use crate::types::{build, JsValue, Value};
use crate::types::{build, JsUndefined, JsValue, Value};
use neon_runtime::raw;

#[cfg(feature = "napi-6")]
Expand Down Expand Up @@ -237,15 +237,36 @@ mod traits {

/// The trait of all object types.
pub trait Object: Value {
fn get_opt<'a, V: Value, C: Context<'a>, K: PropertyKey>(
&self,
cx: &mut C,
key: K,
) -> NeonResult<Option<Handle<'a, V>>> {
let v = self.get_value(cx, key)?;

if v.is_a::<JsUndefined, _>(cx) {
return Ok(None);
}

v.downcast_or_throw(cx).map(Some)
}

fn get_value<'a, C: Context<'a>, K: PropertyKey>(
&self,
cx: &mut C,
key: K,
) -> NeonResult<Handle<'a, JsValue>> {
build(cx.env(), |out| unsafe {
key.get_from(cx, out, self.to_raw())
})
}

fn get<'a, V: Value, C: Context<'a>, K: PropertyKey>(
&self,
cx: &mut C,
key: K,
) -> NeonResult<Handle<'a, V>> {
let v: Handle<JsValue> = build(cx.env(), |out| unsafe {
key.get_from(cx, out, self.to_raw())
})?;
v.downcast_or_throw(cx)
self.get_value(cx, key)?.downcast_or_throw(cx)
}

#[cfg(feature = "napi-6")]
Expand Down

0 comments on commit 06d95ea

Please sign in to comment.