napi_current_env/lib.rs
1use napi::bindgen_prelude::*;
2use tokio::task_local;
3
4task_local! {
5 /// A well-known [`tokio::task_local`] [`napi::Env`] accessible without argument drilling.
6 ///
7 /// This is a pseudo `napi::CURRENT_ENV` that can be relied upon in third-party code that can't take a [`napi::Env`] argument, such as an isomorphic API across NAPI-RS, wasm-bindgen, and native implementation.
8 ///
9 /// **You should use `sync_scope` or `scope` at every NAPI-RS entry point that provides you with a [`napi::Env`]** to ensure that this well-known global is set for all code within your task that might need it.
10 ///
11 /// ```rs
12 /// # use napi_derive::napi;
13 /// # use napi::bindgen_prelude::*;
14 /// # #[allow(unused_imports)]
15 /// # use std::{error::Error, result::Result};
16 /// use napi_current_env::CURRENT_ENV;
17 ///
18 /// #[napi]
19 /// fn print_greeting(env: Env, name: &str) -> napi::Result<()> {
20 /// CURRENT_ENV.sync_scope(env, || {
21 /// // Your code here...
22 /// })
23 /// }
24 ///
25 /// #[napi]
26 /// async fn fetch_data(env: Env, name: &str) -> napi::Result<String> {
27 /// CURRENT_ENV.scope(env, async || {
28 /// // Your async code here...
29 /// })
30 /// }
31 ///
32 /// #[napi(module_exports)]
33 /// fn module_exports(mut exports: Object, env: Env) -> napi::Result<()> {
34 /// CURRENT_ENV.sync_scope(env, || {
35 /// // Your code here...
36 /// })
37 /// }
38 /// ```
39 ///
40 /// # Example
41 ///
42 /// ```rs
43 /// # use napi_derive::napi;
44 /// # use napi::bindgen_prelude::*;
45 /// # #[allow(unused_imports)]
46 /// # use std::{error::Error, result::Result};
47 /// use napi_current_env::CURRENT_ENV;
48 ///
49 /// # fn main() {}
50 /// #
51 ///
52 /// mod another_crate {
53 /// // #[cfg(feature = "napi")]
54 /// fn greet(name: &str) -> napi::Result<String> {
55 /// # use napi::bindgen_prelude::*;
56 /// # #[allow(unused_imports)]
57 /// # use std::{error::Error, result::Result};
58 /// use napi_current_env::CURRENT_ENV;
59 /// let env = CURRENT_ENV.get();
60 /// let file_url_string = env.get_module_file_name()?;
61 /// let message = format!("Hello {} from {}!", name, file_url_string);
62 /// Ok(message)
63 /// }
64 /// // #[cfg(feature = "wasm-bindgen")]
65 /// // ...
66 /// // #[cfg(not(any(feature = "napi", feature = "wasm-bindgen")))]
67 /// // ...
68 /// }
69 ///
70 /// #[napi]
71 /// fn print_greeting(env: Env, name: &str) -> napi::Result<()> {
72 /// CURRENT_ENV.sync_scope(env, || {
73 /// let greeting = another_crate::greet(name)?;
74 /// println!("{}", greeting);
75 /// Ok(())
76 /// })
77 /// }
78 /// ```
79 pub static CURRENT_ENV: Env;
80}