Skip to main content

encore/
frontends.rs

1//! Where the app's frontends are reached.
2//!
3//! [`url`] is a frontend's URL in the environment the code runs in, as to
4//! send a user there or to build a link to one of its pages:
5//!
6//! ```ignore
7//! use encore::frontends;
8//!
9//! let reset = format!("{}/reset?token={token}", frontends::url("web"));
10//! ```
11//!
12//! Looking a frontend's URL up links the calling service to it. Encore reads
13//! the link from the code, as it reads which services a service depends on:
14//! so the name must be a string literal, written as the frontend declares it,
15//! the function must be called directly rather than passed around, and the
16//! call must be in a service.
17
18/// The URL `frontend` is reached at in this environment, without a trailing
19/// slash: a path goes after it, `{url}/reset`. It is the first of the
20/// frontend's origins, as [`crate::env::app_meta`] lists them.
21///
22/// The name is the one the frontend is declared with, in its
23/// `encore.frontend.json` or as the service hosting it: `web_app` does not
24/// find `web-app`.
25///
26/// # Panics
27///
28/// If the runtime knows no URL for `frontend`: the app has no frontend of that
29/// name, which Encore's parser reports, or the environment gives it no
30/// origins.
31pub fn url(frontend: &str) -> &'static str {
32    let meta = crate::runtime::core().app_meta();
33    let origins = meta.frontend(frontend).map(|fe| fe.origins.as_slice());
34    crate::gateways::first_origin(origins).unwrap_or_else(|| {
35        panic!(
36            "encore: no URL is known for frontend {frontend:?}: the app has no frontend of \
37             that name, or the environment gives it no origins"
38        )
39    })
40}