Skip to main content

rustango_cms/api/
locales.rs

1//! `GET /api/v2/locales/` — which content locales this tenant serves.
2//!
3//! Without this a headless client has to hard-code the language list,
4//! and it cannot tell a typo from a real code: `?locale=` falls back to
5//! the tenant default *silently* on anything it doesn't recognise
6//! (`translation::resolve_locale`), so `fr-typo` and `fr` both return
7//! 200 and only the content differs.
8//!
9//! Inactive locales are omitted. A locale that exists but is switched
10//! off is not something a client should offer a reader.
11
12use axum::response::{IntoResponse, Response};
13use axum::Json;
14use rustango::core::Column as _;
15use rustango::extractors::Tenant;
16use rustango::sql::FetcherPool as _;
17
18use crate::locale::Locale;
19
20/// `GET /api/v2/locales/`
21pub async fn list(tenant: Tenant) -> Response {
22    match list_inner(tenant.pool()).await {
23        Ok(resp) => resp,
24        Err(e) => {
25            tracing::error!(target: "rustango_cms::api", error = %e, "locales list failed");
26            crate::api::error::ApiError::internal().into_response()
27        }
28    }
29}
30
31pub async fn list_inner(
32    pool: &rustango::sql::Pool,
33) -> Result<Response, rustango::sql::ExecError> {
34    let locales: Vec<Locale> = Locale::objects()
35        .where_(Locale::active.eq(true))
36        .order_by(&[("sort_order", false), ("code", false)])
37        .fetch(pool)
38        .await?;
39
40    let items: Vec<serde_json::Value> = locales
41        .iter()
42        .map(|l| {
43            serde_json::json!({
44                "code": l.code,
45                "name": l.name,
46                "is_default": l.is_default,
47            })
48        })
49        .collect();
50
51    Ok(Json(serde_json::json!({
52        "meta": {
53            "total_count": items.len(),
54            // Echoed so a client can pick a fallback without scanning.
55            "default": locales.iter().find(|l| l.is_default).map(|l| l.code.clone()),
56        },
57        "items": items,
58    }))
59    .into_response())
60}