[go: up one dir, main page]

worker/
secret_store.rs

1use crate::{
2    send::{SendFuture, SendWrapper},
3    EnvBinding, Fetcher, Result,
4};
5use wasm_bindgen::JsCast;
6use wasm_bindgen_futures::JsFuture;
7
8/// A binding to a Cloudflare Secret Store.
9#[derive(Debug, Clone)]
10pub struct SecretStore(SendWrapper<worker_sys::SecretStoreSys>);
11
12// Allows for attachment to axum router, as Workers will never allow multithreading.
13unsafe impl Send for SecretStore {}
14unsafe impl Sync for SecretStore {}
15
16impl EnvBinding for SecretStore {
17    const TYPE_NAME: &'static str = "Fetcher";
18}
19
20impl JsCast for SecretStore {
21    fn instanceof(val: &wasm_bindgen::JsValue) -> bool {
22        Fetcher::instanceof(val)
23    }
24
25    fn unchecked_from_js(val: wasm_bindgen::JsValue) -> Self {
26        let fetcher = Fetcher::unchecked_from_js(val);
27        Self::from(fetcher)
28    }
29
30    fn unchecked_from_js_ref(val: &wasm_bindgen::JsValue) -> &Self {
31        unsafe { &*(val as *const wasm_bindgen::JsValue as *const Self) }
32    }
33}
34
35impl AsRef<wasm_bindgen::JsValue> for SecretStore {
36    fn as_ref(&self) -> &wasm_bindgen::JsValue {
37        self.0.as_ref()
38    }
39}
40
41impl From<wasm_bindgen::JsValue> for SecretStore {
42    fn from(val: wasm_bindgen::JsValue) -> Self {
43        Self::unchecked_from_js(val)
44    }
45}
46
47impl From<Fetcher> for SecretStore {
48    fn from(fetcher: Fetcher) -> Self {
49        Self(SendWrapper::new(fetcher.into_rpc()))
50    }
51}
52
53impl From<SecretStore> for wasm_bindgen::JsValue {
54    fn from(secret_store: SecretStore) -> Self {
55        let sys_obj: &worker_sys::SecretStoreSys = secret_store.0.as_ref();
56        sys_obj.clone().into()
57    }
58}
59
60impl SecretStore {
61    /// Get a secret value from the secret store.
62    /// Returns None if the secret doesn't exist.
63    pub async fn get(&self) -> Result<Option<String>> {
64        let promise = match self.0.get() {
65            Ok(p) => p,
66            Err(_) => return Ok(None), // Secret not found
67        };
68
69        let fut = SendFuture::new(JsFuture::from(promise));
70
71        let output = match fut.await {
72            Ok(val) => val,
73            Err(_) => return Ok(None), // Promise rejected, secret not found
74        };
75
76        if output.is_null() || output.is_undefined() {
77            Ok(None)
78        } else {
79            Ok(Some(::serde_wasm_bindgen::from_value(output)?))
80        }
81    }
82}