Skip to main content

mini_apm_admin/web/
project_context.rs

1use tower_cookies::Cookies;
2
3use mini_apm::{DbPool, models::project::Project};
4
5pub const PROJECT_COOKIE: &str = "miniapm_project";
6
7/// Extracts current project context from cookie
8#[derive(Clone, Debug)]
9pub struct WebProjectContext {
10    pub current_project: Option<Project>,
11    pub projects: Vec<Project>,
12    pub projects_enabled: bool,
13}
14
15impl WebProjectContext {
16    pub fn project_id(&self) -> Option<i64> {
17        self.current_project.as_ref().map(|p| p.id)
18    }
19
20    /// Check if the given project ID is the current project (for template use)
21    pub fn is_current_project(&self, id: &i64) -> bool {
22        self.current_project.as_ref().map(|p| p.id) == Some(*id)
23    }
24
25    /// Returns true if project selector should be shown (more than 1 project)
26    pub fn show_selector(&self) -> bool {
27        self.projects_enabled && self.projects.len() > 1
28    }
29}
30
31pub fn get_project_context(pool: &DbPool, cookies: &Cookies) -> WebProjectContext {
32    let projects_enabled = std::env::var("ENABLE_PROJECTS")
33        .map(|v| v == "1" || v.to_lowercase() == "true")
34        .unwrap_or(false);
35
36    if !projects_enabled {
37        return WebProjectContext {
38            current_project: None,
39            projects: vec![],
40            projects_enabled: false,
41        };
42    }
43
44    let projects = mini_apm::models::project::list_all(pool).unwrap_or_default();
45
46    // Get project slug from cookie
47    let project_slug = cookies.get(PROJECT_COOKIE).map(|c| c.value().to_string());
48
49    let current_project = match project_slug {
50        Some(slug) => projects.iter().find(|p| p.slug == slug).cloned(),
51        None => projects.first().cloned(),
52    };
53
54    WebProjectContext {
55        current_project,
56        projects,
57        projects_enabled,
58    }
59}