encore-dev 2.0.0-beta.19

Rust SDK for Encore applications
Documentation
//! Resolving URLs for the application's API gateways.
//!
//! Call [`url`] to get a gateway's public base URL in the current environment,
//! for example to share a webhook or API address with an external client:
//!
//! ```ignore
//! use encore::gateways;
//!
//! let callback = format!("{}/webhooks/stripe", gateways::url("api"));
//! ```
//!
//! To call another service inside the application, use [`crate::services`]
//! rather than going through a gateway.
//!
//! Looking up a gateway URL records a dependency from the calling service to
//! that gateway. Because Encore parses this dependency statically, pass the
//! gateway's declared name as a string literal, call `gateways::url` directly
//! (rather than through a function pointer), and make the call inside a service.

/// Returns the base URL for `gateway` in the current environment, without a
/// trailing slash (so paths can be appended directly, e.g.
/// `{url}/webhooks/stripe`).
///
/// This returns the first origin listed for the gateway in
/// [`crate::env::app_meta`]. `gateway` must match the exact name declared in
/// `encore.gateway.json` or the hosting service (for example, `public_api` does
/// not match `public-api`).
///
/// # Panics
///
/// Panics if no URL is configured for `gateway` — either because the app has no
/// gateway with that name or because the environment provides no origins for it.
pub fn url(gateway: &str) -> &'static str {
    let meta = crate::runtime::core().app_meta();
    let Some(gw) = meta.gateway(gateway) else {
        panic!("encore: no URL configured for gateway {gateway:?}: the app has no gateway with that name")
    };
    first_origin(Some(&gw.origins)).unwrap_or_else(|| {
        panic!(
            "encore: no URL configured for gateway {gateway:?}: this environment provides no origins for it"
        )
    })
}

/// A component's URL: the first of its `origins`, without a trailing slash.
/// `None` for no component, or one with no origins.
pub(crate) fn first_origin(origins: Option<&[String]>) -> Option<&str> {
    let url = origins?.first()?.trim_end_matches('/');
    (!url.is_empty()).then_some(url)
}

#[cfg(test)]
mod tests {
    use super::first_origin;

    fn origins(list: &[&str]) -> Vec<String> {
        list.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn the_url_is_the_first_origin_without_a_trailing_slash() {
        let list = origins(&["https://example.com/", "https://*.example.com", "*"]);
        assert_eq!(first_origin(Some(&list)), Some("https://example.com"));
        let list = origins(&["http://web.localhost:4000"]);
        assert_eq!(first_origin(Some(&list)), Some("http://web.localhost:4000"));
    }

    #[test]
    fn no_component_or_no_origins_is_no_url() {
        assert_eq!(first_origin(None), None);
        assert_eq!(first_origin(Some(&[])), None);
        assert_eq!(first_origin(Some(&origins(&[""]))), None);
    }
}