sz_rust_orm_facade/data_scope/modes/
custom.rs1use super::ModeEvaluator;
4use crate::data_scope::context::DataScopeContext;
5use crate::data_scope::custom::CustomGeneratorRegistry;
6use crate::data_scope::error::DataScopeError;
7use crate::data_scope::rule::DataScopeRule;
8use crate::repository::WhereCondition;
9use async_trait::async_trait;
10use std::sync::Arc;
11
12pub struct CustomMode {
14 registry: Arc<CustomGeneratorRegistry>,
15}
16
17impl CustomMode {
18 pub fn new(registry: Arc<CustomGeneratorRegistry>) -> Self {
19 Self { registry }
20 }
21}
22
23#[async_trait]
24impl ModeEvaluator for CustomMode {
25 async fn evaluate(
26 &self,
27 ctx: &DataScopeContext,
28 rule: &DataScopeRule,
29 ) -> Result<Vec<WhereCondition>, DataScopeError> {
30 let generator_name = rule.custom_generator.as_deref().ok_or_else(|| {
31 DataScopeError::InvalidRule("CUSTOM mode requires custom_generator".into())
32 })?;
33 let generator = self
34 .registry
35 .get(generator_name)
36 .ok_or_else(|| DataScopeError::GeneratorNotFound(generator_name.to_string()))?;
37 let conditions = generator.generate(ctx).await?;
38 if conditions.is_empty() {
39 return Err(DataScopeError::UnsafeCustomCondition(
40 "custom generator returned empty conditions".into(),
41 ));
42 }
43 Ok(conditions)
44 }
45}
46
47#[cfg(test)]
48mod tests {
49 use super::*;
50 use crate::data_scope::custom::CustomGeneratorRegistry;
51 use crate::data_scope::rule::DataScopeMode;
52
53 #[tokio::test]
54 async fn test_custom_mode_missing_generator_name() {
55 let registry = Arc::new(CustomGeneratorRegistry::new());
56 let mode = CustomMode::new(registry);
57 let ctx = DataScopeContext::new(1, 5, false);
58 let rule = DataScopeRule::new("order", DataScopeMode::Custom);
59 let err = mode.evaluate(&ctx, &rule).await.unwrap_err();
60 assert_eq!(err.error_code(), "DATA_SCOPE_INVALID_RULE");
61 }
62
63 #[tokio::test]
64 async fn test_custom_mode_generator_not_found() {
65 let registry = Arc::new(CustomGeneratorRegistry::new());
66 let mode = CustomMode::new(registry);
67 let ctx = DataScopeContext::new(1, 5, false);
68 let rule =
69 DataScopeRule::new("order", DataScopeMode::Custom).with_custom_generator("nonexistent");
70 let err = mode.evaluate(&ctx, &rule).await.unwrap_err();
71 assert_eq!(err.error_code(), "DATA_SCOPE_GENERATOR_NOT_FOUND");
72 }
73}