spin_sdk/variables.rs
1//! Application variable lookup.
2//!
3//! Component variables must be defined in the application
4//! manifest, in the `[component.<name>.variables]` section.
5//! Component variables typically use template syntax to
6//! derive values from application variables, which are
7//! the only variables that may be overridden directly (for
8//! example, on the Spin command line).
9//!
10//! # Examples
11//!
12//! Get the value of a component variable.
13//!
14//! ```no_run
15//! # async fn run() -> anyhow::Result<()> {
16//! let region = spin_sdk::variables::get("region_id").await?;
17//! let regional_url = format!("https://{region}.db.example.com");
18//! # Ok(())
19//! # }
20//! ```
21//!
22//! Fail gracefully if a variable is not set.
23//!
24//! ```no_run
25//! use spin_sdk::variables::Error;
26//!
27//! # async fn run() -> anyhow::Result<()> {
28//! let favourite = match spin_sdk::variables::get("favourite").await {
29//! Ok(value) => value,
30//! Err(Error::Undefined(_)) => "not playing favourites".to_owned(),
31//! Err(e) => anyhow::bail!(e),
32//! };
33//! # Ok(())
34//! # }
35//! ```
36
37#[doc(hidden)]
38/// Module containing wit bindgen generated code.
39///
40/// This is only meant for internal consumption.
41pub mod wit {
42 #![allow(missing_docs)]
43 use crate::wit_bindgen;
44
45 wit_bindgen::generate!({
46 runtime_path: "crate::wit_bindgen::rt",
47 world: "spin-sdk-variables",
48 path: "wit",
49 generate_all,
50 });
51
52 pub use spin::variables::variables;
53}
54
55#[doc(inline)]
56pub use wit::variables::Error;
57
58/// Get an application variable value for the current component.
59///
60/// The name must match one defined in in the component manifest.
61pub async fn get(key: impl AsRef<str>) -> Result<String, Error> {
62 wit::variables::get(key.as_ref().to_string()).await
63}