Skip to content

Commit 914eee6

Browse files
committed
Support object variables in wrangler toml.
Example: ```toml [vars] VAR = { a = 1, b = "hey" } [vars.VAR] a = 1 b = "hey" ```
1 parent 9e1b665 commit 914eee6

File tree

1 file changed

+48
-2
lines changed

1 file changed

+48
-2
lines changed

worker/src/env.rs

Lines changed: 48 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ use crate::{durable::ObjectNamespace, Bucket, DynamicDispatcher, Fetcher, Result
88
use crate::{error::Error, hyperdrive::Hyperdrive};
99

1010
use js_sys::Object;
11+
use serde::de::DeserializeOwned;
1112
use wasm_bindgen::{prelude::*, JsCast, JsValue};
1213
use worker_kv::KvStore;
1314

@@ -42,12 +43,24 @@ impl Env {
4243
self.get_binding::<Secret>(binding)
4344
}
4445

45-
/// Environment variables are defined via the `[vars]` configuration in your wrangler.toml file
46-
/// and are always plaintext values.
46+
/// Get an environment variable defined in the [vars] section of your wrangler.toml or a secret
47+
/// defined using `wrangler secret` as a plaintext value.
48+
///
49+
/// See: <https://developers.cloudflare.com/workers/configuration/environment-variables/>
4750
pub fn var(&self, binding: &str) -> Result<Var> {
4851
self.get_binding::<Var>(binding)
4952
}
5053

54+
/// Get an environment variable defined in the [vars] section of your wrangler.toml that is
55+
/// defined as an object.
56+
///
57+
/// See: <https://developers.cloudflare.com/workers/configuration/environment-variables/>
58+
pub fn object_var<T: DeserializeOwned>(&self, binding: &str) -> Result<T> {
59+
Ok(serde_wasm_bindgen::from_value(
60+
self.get_binding::<JsValueWrapper>(binding)?.0,
61+
)?)
62+
}
63+
5164
/// Access a Workers KV namespace by the binding name configured in your wrangler.toml file.
5265
pub fn kv(&self, binding: &str) -> Result<KvStore> {
5366
KvStore::from_this(self, binding).map_err(From::from)
@@ -153,6 +166,39 @@ impl Display for StringBinding {
153166
}
154167
}
155168

169+
#[repr(transparent)]
170+
struct JsValueWrapper(JsValue);
171+
172+
impl EnvBinding for JsValueWrapper {
173+
const TYPE_NAME: &'static str = "Object";
174+
}
175+
176+
impl JsCast for JsValueWrapper {
177+
fn instanceof(_: &JsValue) -> bool {
178+
true
179+
}
180+
181+
fn unchecked_from_js(val: JsValue) -> Self {
182+
Self(val)
183+
}
184+
185+
fn unchecked_from_js_ref(val: &JsValue) -> &Self {
186+
unsafe { std::mem::transmute(val) }
187+
}
188+
}
189+
190+
impl From<JsValueWrapper> for wasm_bindgen::JsValue {
191+
fn from(value: JsValueWrapper) -> Self {
192+
value.0
193+
}
194+
}
195+
196+
impl AsRef<JsValue> for JsValueWrapper {
197+
fn as_ref(&self) -> &JsValue {
198+
&self.0
199+
}
200+
}
201+
156202
/// A string value representing a binding to a secret in a Worker.
157203
#[doc(inline)]
158204
pub use StringBinding as Secret;

0 commit comments

Comments
 (0)