Skip to main content

romance_core/addon/
validation.rs

1use crate::addon::Addon;
2use anyhow::Result;
3use std::path::Path;
4
5pub struct ValidationAddon;
6
7impl Addon for ValidationAddon {
8    fn name(&self) -> &str {
9        "validation"
10    }
11
12    fn check_prerequisites(&self, project_root: &Path) -> Result<()> {
13        super::check_romance_project(project_root)
14    }
15
16    fn is_already_installed(&self, project_root: &Path) -> bool {
17        project_root
18            .join("backend/src/validation.rs")
19            .exists()
20    }
21
22    fn install(&self, project_root: &Path) -> Result<()> {
23        install_validation(project_root)
24    }
25
26    fn uninstall(&self, project_root: &Path) -> Result<()> {
27        use colored::Colorize;
28
29        println!("{}", "Uninstalling validation...".bold());
30
31        // Delete files
32        if super::remove_file_if_exists(&project_root.join("backend/src/validation.rs"))? {
33            println!("  {} backend/src/validation.rs", "delete".red());
34        }
35
36        // Remove mod declaration from main.rs
37        super::remove_mod_from_main(project_root, "validation")?;
38
39        // Remove feature flag
40        super::remove_feature_flag(project_root, "validation")?;
41
42        // Regenerate AI context
43        crate::ai_context::regenerate(project_root).ok();
44
45        println!();
46        println!("{}", "Validation uninstalled successfully.".green().bold());
47
48        Ok(())
49    }
50}
51
52fn install_validation(project_root: &Path) -> Result<()> {
53    use crate::template::TemplateEngine;
54    use crate::utils;
55    use colored::Colorize;
56    use tera::Context;
57
58    println!("{}", "Installing validation...".bold());
59
60    let engine = TemplateEngine::new()?;
61    let ctx = Context::new();
62
63    // Generate validation middleware
64    let content = engine.render("addon/validation/validate_middleware.rs.tera", &ctx)?;
65    utils::write_file(
66        &project_root.join("backend/src/validation.rs"),
67        &content,
68    )?;
69    println!("  {} backend/src/validation.rs", "create".green());
70
71    // Add mod declaration to main.rs
72    super::add_mod_to_main(project_root, "validation")?;
73
74    // Add validator dependencies to Cargo.toml
75    crate::generator::auth::insert_cargo_dependency(
76        &project_root.join("backend/Cargo.toml"),
77        &[
78            ("validator", r#"{ version = "0.19", features = ["derive"] }"#),
79        ],
80    )?;
81
82    // Update romance.toml features
83    super::update_feature_flag(project_root, "validation", true)?;
84
85    println!();
86    println!("{}", "Validation installed successfully!".green().bold());
87    println!("  Entity fields now support validation rules: name:string[min=3,max=100]");
88
89    Ok(())
90}