Skip to main content

workflow_core/
env.rs

1//!
2//! Access to environment variables when running natively or
3//! on top of Node.js (via `process.env`).
4//!
5
6use cfg_if::cfg_if;
7use std::env::VarError;
8
9/// Returns the value of the environment variable `_key`, reading from the
10/// process environment natively or from `process.env` under Node.js.
11/// Returns [`VarError::NotPresent`] if the variable is unset.
12pub fn var(_key: &str) -> Result<String, VarError> {
13    cfg_if! {
14        if #[cfg(target_arch = "wasm32")] {
15            if crate::runtime::is_node() {
16                match get_nodejs_env_var(_key)? {
17                    Some(v) => Ok(v),
18                    None => {
19                        Err(VarError::NotPresent)
20                    }
21                }
22            } else {
23                panic!("workflow_core::env::var() is not supported on this platform (must be native of nodejs)");
24            }
25        } else {
26            std::env::var(_key)
27        }
28    }
29}
30
31#[allow(dead_code)]
32fn get_nodejs_env_var(key: &str) -> Result<Option<String>, VarError> {
33    use js_sys::{Object, Reflect};
34    use wasm_bindgen::prelude::*;
35
36    let process = Reflect::get(&js_sys::global(), &"process".into())
37        .expect("Unable to get nodejs process global");
38    let env = Reflect::get(&process, &"env".into()).expect("Unable to get nodejs process.env");
39    let object = Object::from(env);
40    let value =
41        Reflect::get(&object, &JsValue::from_str(key)).map_err(|_err| VarError::NotPresent)?;
42    Ok(value.as_string())
43}