napi_h/js_values/
global.rs

1use std::convert::TryInto;
2
3use super::*;
4use crate::{bindgen_runtime::FromNapiValue, Env};
5
6pub struct JsGlobal(pub(crate) Value);
7
8pub struct JsTimeout(pub(crate) Value);
9
10pub struct JSON(pub(crate) Value);
11
12impl FromNapiValue for JSON {
13  unsafe fn from_napi_value(env: sys::napi_env, napi_val: sys::napi_value) -> Result<Self> {
14    Ok(JSON(Value {
15      env,
16      value: napi_val,
17      value_type: ValueType::Object,
18    }))
19  }
20}
21
22impl JSON {
23  pub fn stringify<V: NapiRaw>(&self, value: V) -> Result<std::string::String> {
24    let func: JsFunction = self.get_named_property_unchecked("stringify")?;
25    let result = func
26      .call(None, &[value])
27      .map(|ret| unsafe { ret.cast::<JsString>() })?;
28    result.into_utf8()?.as_str().map(|s| s.to_owned())
29  }
30}
31
32impl JsGlobal {
33  pub fn set_interval(&self, handler: JsFunction, interval: f64) -> Result<JsTimeout> {
34    let func: JsFunction = self.get_named_property_unchecked("setInterval")?;
35    func
36      .call(
37        None,
38        &[
39          handler.into_unknown(),
40          unsafe { Env::from_raw(self.0.env) }
41            .create_double(interval)?
42            .into_unknown(),
43        ],
44      )
45      .and_then(|ret| ret.try_into())
46  }
47
48  pub fn clear_interval(&self, timer: JsTimeout) -> Result<JsUndefined> {
49    let func: JsFunction = self.get_named_property_unchecked("clearInterval")?;
50    func
51      .call(None, &[timer.into_unknown()])
52      .and_then(|ret| ret.try_into())
53  }
54
55  pub fn set_timeout(&self, handler: JsFunction, interval: f64) -> Result<JsTimeout> {
56    let func: JsFunction = self.get_named_property_unchecked("setTimeout")?;
57    func
58      .call(
59        None,
60        &[
61          handler.into_unknown(),
62          unsafe { Env::from_raw(self.0.env) }
63            .create_double(interval)?
64            .into_unknown(),
65        ],
66      )
67      .and_then(|ret| ret.try_into())
68  }
69
70  pub fn clear_timeout(&self, timer: JsTimeout) -> Result<JsUndefined> {
71    let func: JsFunction = self.get_named_property_unchecked("clearTimeout")?;
72    func
73      .call(None, &[timer.into_unknown()])
74      .and_then(|ret| ret.try_into())
75  }
76}