encore-dev 2.0.0-beta.13

Rust SDK for Encore applications
Documentation
//! Where the app's gateways are reached.
//!
//! [`url`] is a gateway's URL in the environment the code runs in, as to
//! hand a client outside the app the address of its API:
//!
//! ```ignore
//! use encore::gateways;
//!
//! let callback = format!("{}/webhooks/stripe", gateways::url("api"));
//! ```
//!
//! A service calls the app's other services with [`crate::services`], not
//! through a gateway.
//!
//! Looking a gateway's URL up links the calling service to it. Encore reads
//! the link from the code, as it reads which services a service depends on:
//! so the name must be a string literal, written as the gateway declares it,
//! the function must be called directly rather than passed around, and the
//! call must be in a service.

/// The URL `gateway` is reached at in this environment, without a trailing
/// slash: a path goes after it, `{url}/webhooks/stripe`. It is the first of
/// the gateway's origins, as [`crate::env::app_meta`] lists them.
///
/// The name is the one the gateway is declared with, in its
/// `encore.gateway.json` or as the service hosting it: `public_api` does not
/// find `public-api`.
///
/// # Panics
///
/// If the runtime knows no URL for `gateway`: the app has no gateway of that
/// name, which Encore's parser reports, or the environment gives it no
/// origins.
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 is known for gateway {gateway:?}: the app has no gateway of that name"
        )
    };
    first_origin(Some(&gw.origins)).unwrap_or_else(|| {
        panic!(
            "encore: no URL is known for gateway {gateway:?}: the environment gives it no origins"
        )
    })
}

/// 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);
    }
}