Skip to main content

spin_sdk/
variables.rs

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