Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support object variables in wrangler toml. #677

Merged
merged 3 commits into from
Dec 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions worker-sandbox/src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ use crate::SomeSharedData;
use super::ApiData;
use futures_util::StreamExt;
use futures_util::TryStreamExt;
use serde::Deserialize;
use serde::Serialize;
use std::time::Duration;
use worker::Env;
use worker::{console_log, Date, Delay, Request, Response, ResponseBody, ResponseBuilder, Result};
Expand Down Expand Up @@ -92,6 +94,16 @@ pub async fn handle_var(_req: Request, env: Env, _data: SomeSharedData) -> Resul
Response::ok(env.var("SOME_VARIABLE")?.to_string())
}

pub async fn handle_object_var(_req: Request, env: Env, _: SomeSharedData) -> Result<Response> {
#[derive(Serialize, Deserialize, PartialEq, Eq)]
struct Obj {
foo: i32,
bar: String,
}
let obj = env.object_var::<Obj>("SOME_OBJECT_VARIABLE")?;
Response::from_json(&obj)
}

pub async fn handle_bytes(_req: Request, _env: Env, _data: SomeSharedData) -> Result<Response> {
Response::from_bytes(vec![1, 2, 3, 4, 5, 6, 7])
}
Expand Down
2 changes: 2 additions & 0 deletions worker-sandbox/src/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ pub fn make_router(data: SomeSharedData, env: Env) -> axum::Router {
.route("/durable/put-raw", get(handler!(alarm::handle_put_raw)))
.route("/durable/websocket", get(handler!(alarm::handle_websocket)))
.route("/var", get(handler!(request::handle_var)))
.route("/object-var", get(handler!(request::handle_object_var)))
.route("/secret", get(handler!(request::handle_secret)))
.route("/kv/:key/:value", post(handler!(kv::handle_post_key_value)))
.route("/bytes", get(handler!(request::handle_bytes)))
Expand Down Expand Up @@ -268,6 +269,7 @@ pub fn make_router<'a>(data: SomeSharedData) -> Router<'a, SomeSharedData> {
.get_async("/durable/websocket", handler!(alarm::handle_websocket))
.get_async("/secret", handler!(request::handle_secret))
.get_async("/var", handler!(request::handle_var))
.get_async("/object-var", handler!(request::handle_object_var))
.post_async("/kv/:key/:value", handler!(kv::handle_post_key_value))
.get_async("/bytes", handler!(request::handle_bytes))
.post_async("/api-data", handler!(request::handle_api_data))
Expand Down
5 changes: 5 additions & 0 deletions worker-sandbox/tests/mf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,11 @@ export const mf = new Miniflare({
bindings: {
EXAMPLE_SECRET: "example",
SOME_SECRET: "secret!",
SOME_VARIABLE: "some value",
SOME_OBJECT_VARIABLE: {
foo: 42,
bar: "string"
},
},
durableObjects: {
COUNTER: "Counter",
Expand Down
10 changes: 10 additions & 0 deletions worker-sandbox/tests/request.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,16 @@ test("some secret", async () => {
expect(await resp.text()).toBe("secret!");
});

test("some var", async () => {
const resp = await mf.dispatchFetch("https://fake.host/var");
expect(await resp.text()).toBe("some value");
});

test("some object var", async () => {
const resp = await mf.dispatchFetch("https://fake.host/object-var");
expect(await resp.json()).toStrictEqual({ foo: 42, bar: "string" });
});

test("kv key value", async () => {
const resp = await mf.dispatchFetch("https://fake.host/kv/a/b", {
method: "POST",
Expand Down
4 changes: 3 additions & 1 deletion worker-sandbox/wrangler.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ kv_namespaces = [
{ binding = "FILE_SIZES", id = "FILE_SIZES", preview_id = "FILE_SIZES" },
]

vars = { SOME_VARIABLE = "some value" }
[vars]
SOME_VARIABLE = "some value"
SOME_OBJECT_VARIABLE = { foo = 42, bar = "string" }

[[services]]
binding = "remote"
Expand Down
50 changes: 48 additions & 2 deletions worker/src/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use crate::{durable::ObjectNamespace, Bucket, DynamicDispatcher, Fetcher, Result
use crate::{error::Error, hyperdrive::Hyperdrive};

use js_sys::Object;
use serde::de::DeserializeOwned;
use wasm_bindgen::{prelude::*, JsCast, JsValue};
use worker_kv::KvStore;

Expand Down Expand Up @@ -42,12 +43,24 @@ impl Env {
self.get_binding::<Secret>(binding)
}

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

/// Get an environment variable defined in the [vars] section of your wrangler.toml that is
/// defined as an object.
///
/// See: <https://developers.cloudflare.com/workers/configuration/environment-variables/>
pub fn object_var<T: DeserializeOwned>(&self, binding: &str) -> Result<T> {
zebp marked this conversation as resolved.
Show resolved Hide resolved
Ok(serde_wasm_bindgen::from_value(
self.get_binding::<JsValueWrapper>(binding)?.0,
)?)
}

/// Access a Workers KV namespace by the binding name configured in your wrangler.toml file.
pub fn kv(&self, binding: &str) -> Result<KvStore> {
KvStore::from_this(self, binding).map_err(From::from)
Expand Down Expand Up @@ -153,6 +166,39 @@ impl Display for StringBinding {
}
}

#[repr(transparent)]
struct JsValueWrapper(JsValue);

impl EnvBinding for JsValueWrapper {
const TYPE_NAME: &'static str = "Object";
}

impl JsCast for JsValueWrapper {
fn instanceof(_: &JsValue) -> bool {
true
}

fn unchecked_from_js(val: JsValue) -> Self {
Self(val)
}

fn unchecked_from_js_ref(val: &JsValue) -> &Self {
unsafe { std::mem::transmute(val) }
}
}

impl From<JsValueWrapper> for wasm_bindgen::JsValue {
fn from(value: JsValueWrapper) -> Self {
value.0
}
}

impl AsRef<JsValue> for JsValueWrapper {
fn as_ref(&self) -> &JsValue {
&self.0
}
}

/// A string value representing a binding to a secret in a Worker.
#[doc(inline)]
pub use StringBinding as Secret;
Expand Down
Loading