encore/gateways.rs
1//! Where the app's gateways are reached.
2//!
3//! [`url`] is a gateway's URL in the environment the code runs in, as to
4//! hand a client outside the app the address of its API:
5//!
6//! ```ignore
7//! use encore::gateways;
8//!
9//! let callback = format!("{}/webhooks/stripe", gateways::url("api"));
10//! ```
11//!
12//! A service calls the app's other services with [`crate::services`], not
13//! through a gateway.
14//!
15//! Looking a gateway's URL up links the calling service to it. Encore reads
16//! the link from the code, as it reads which services a service depends on:
17//! so the name must be a string literal, written as the gateway declares it,
18//! the function must be called directly rather than passed around, and the
19//! call must be in a service.
20
21/// The URL `gateway` is reached at in this environment, without a trailing
22/// slash: a path goes after it, `{url}/webhooks/stripe`. It is the first of
23/// the gateway's origins, as [`crate::env::app_meta`] lists them.
24///
25/// The name is the one the gateway is declared with, in its
26/// `encore.gateway.json` or as the service hosting it: `public_api` does not
27/// find `public-api`.
28///
29/// # Panics
30///
31/// If the runtime knows no URL for `gateway`: the app has no gateway of that
32/// name, which Encore's parser reports, or the environment gives it no
33/// origins.
34pub fn url(gateway: &str) -> &'static str {
35 let meta = crate::runtime::core().app_meta();
36 let Some(gw) = meta.gateway(gateway) else {
37 panic!(
38 "encore: no URL is known for gateway {gateway:?}: the app has no gateway of that name"
39 )
40 };
41 first_origin(Some(&gw.origins)).unwrap_or_else(|| {
42 panic!(
43 "encore: no URL is known for gateway {gateway:?}: the environment gives it no origins"
44 )
45 })
46}
47
48/// A component's URL: the first of its `origins`, without a trailing slash.
49/// `None` for no component, or one with no origins.
50pub(crate) fn first_origin(origins: Option<&[String]>) -> Option<&str> {
51 let url = origins?.first()?.trim_end_matches('/');
52 (!url.is_empty()).then_some(url)
53}
54
55#[cfg(test)]
56mod tests {
57 use super::first_origin;
58
59 fn origins(list: &[&str]) -> Vec<String> {
60 list.iter().map(|s| s.to_string()).collect()
61 }
62
63 #[test]
64 fn the_url_is_the_first_origin_without_a_trailing_slash() {
65 let list = origins(&["https://example.com/", "https://*.example.com", "*"]);
66 assert_eq!(first_origin(Some(&list)), Some("https://example.com"));
67 let list = origins(&["http://web.localhost:4000"]);
68 assert_eq!(first_origin(Some(&list)), Some("http://web.localhost:4000"));
69 }
70
71 #[test]
72 fn no_component_or_no_origins_is_no_url() {
73 assert_eq!(first_origin(None), None);
74 assert_eq!(first_origin(Some(&[])), None);
75 assert_eq!(first_origin(Some(&origins(&[""]))), None);
76 }
77}