Skip to main content

br_addon/
module.rs

1use crate::action::Action;
2use crate::PLUGIN_TOOLS;
3use crate::{Tools, GLOBAL_DATA};
4#[cfg(any(
5    feature = "mysql",
6    feature = "sqlite",
7    feature = "mssql",
8    feature = "pgsql"
9))]
10use br_db::Db;
11use json::{array, object, JsonValue};
12use std::any::type_name;
13
14/// 模型配置
15pub trait Module: Send + Sync + 'static {
16    /// =================基础配置=============================
17    /// 插件名称
18    /// NOTE: 使用 Box::leak 返回 'static str,每个类型只会泄漏一次
19    fn _name(&self) -> &'static str {
20        let name = type_name::<Self>()
21            .split("::")
22            .nth(3)
23            .unwrap_or_default()
24            .to_lowercase();
25        Box::leak(name.into_boxed_str())
26    }
27    /// 模型名称
28    /// xxx.xxx
29    /// NOTE: 使用 Box::leak 返回 'static str,每个类型只会泄漏一次
30    fn module_name(&self) -> &'static str {
31        let t = type_name::<Self>().split("::").collect::<Vec<&str>>();
32        let name = if t.len() > 3 {
33            format!("{}.{}", t[2], t[3])
34        } else {
35            String::new()
36        };
37        Box::leak(name.into_boxed_str())
38    }
39    /// 模型标题
40    fn title(&self) -> &'static str;
41    /// 模型描述
42    fn description(&self) -> &'static str {
43        ""
44    }
45    /// 可用范围
46    fn tags(&self) -> &'static [&'static str] {
47        &["admin", "org"]
48    }
49    /// =================视图配置=============================
50    /// 模型icon
51    fn icon(&self) -> &'static str {
52        ""
53    }
54    /// =================数据库配置=============================
55    /// 是否数据表
56    fn table(&self) -> bool {
57        false
58    }
59    /// 数据库表名称
60    fn _table_name(&self) -> &'static str {
61        let mut it = type_name::<Self>().rsplitn(4, "::");
62        let _ = it.next().unwrap_or(""); // 最末段
63        let t2 = it.next().unwrap_or("");
64        let t3 = it.next().unwrap_or("");
65        let s = format!("{t3}_{t2}").to_lowercase();
66        Box::leak(s.into_boxed_str())
67    }
68    /// 主键
69    fn table_key(&self) -> &'static str {
70        "id"
71    }
72    /// 唯一索引
73    fn table_unique(&self) -> &'static [&'static str] {
74        &[]
75    }
76    /// 查询索引
77    fn table_index(&self) -> &'static [&'static [&'static str]] {
78        &[]
79    }
80    /// 是否分区
81    fn table_partition(&self) -> bool {
82        false
83    }
84    /// 分区配置
85    /// *列名
86    /// *分区key
87    /// *实例 array![str, array![range1, range2, range3...]]
88    /// *如果在已有分区的情况下想要修改分区的参照列,先要将当前分区代码删除后刷库,然后写新的分区规则再刷库
89    fn table_partition_columns(&self) -> JsonValue {
90        array![]
91    }
92    /// =================功能配置=============================
93    /// 加载功能
94    /// * name 功能名称
95    fn action(&mut self, name: &str) -> Result<Box<dyn Action>, String>;
96    /// 模型字段
97    fn fields(&mut self) -> JsonValue {
98        object! {}
99    }
100    /// 初始化数据
101    fn init_data(&mut self) -> JsonValue {
102        array![]
103    }
104    /// 使用工具
105    fn tools(&mut self) -> Tools {
106        PLUGIN_TOOLS.get().expect("tools not initialized").clone()
107    }
108    /// 设置全局变量
109    fn set_global_data(&mut self, key: &str, value: JsonValue) {
110        GLOBAL_DATA.with(|data| {
111            data.borrow_mut()[key] = value;
112        });
113    }
114    /// 获取全局变量数据
115    fn get_global_data(&mut self) -> JsonValue {
116        GLOBAL_DATA.with(|data| data.borrow().clone())
117    }
118    /// 获取全局变量指定字段数据
119    fn get_global_data_key(&mut self, key: &str) -> JsonValue {
120        GLOBAL_DATA.with(|data| data.borrow()[key].clone())
121    }
122    #[cfg(any(
123        feature = "mysql",
124        feature = "sqlite",
125        feature = "mssql",
126        feature = "pgsql"
127    ))]
128    fn db_table(&mut self) -> Db {
129        let table = self._table_name();
130        self.tools().db.table(table).clone()
131    }
132    #[cfg(any(
133        feature = "mysql",
134        feature = "sqlite",
135        feature = "mssql",
136        feature = "pgsql"
137    ))]
138    fn db_find(&mut self, id: &str) -> JsonValue {
139        self.db_table().where_and("id", "=", id.into()).find()
140    }
141    #[cfg(any(
142        feature = "mysql",
143        feature = "sqlite",
144        feature = "mssql",
145        feature = "pgsql"
146    ))]
147    fn db_select(&mut self, ids: &str) -> JsonValue {
148        self.db_table().where_and("id", "in", ids.into()).select()
149    }
150    #[cfg(any(
151        feature = "mysql",
152        feature = "sqlite",
153        feature = "mssql",
154        feature = "pgsql"
155    ))]
156    fn db_insert(&mut self, data: JsonValue) -> String {
157        let res = self.db_table().insert(data);
158        res.to_string()
159    }
160    #[cfg(any(
161        feature = "mysql",
162        feature = "sqlite",
163        feature = "mssql",
164        feature = "pgsql"
165    ))]
166    fn db_delete(&mut self, id: &str) -> usize {
167        let delete = self.db_table().where_and("id", "=", id.into()).delete();
168        delete.as_usize().unwrap_or(0)
169    }
170    #[cfg(any(
171        feature = "mysql",
172        feature = "sqlite",
173        feature = "mssql",
174        feature = "pgsql"
175    ))]
176    fn db_update(&mut self, id: &str, data: JsonValue) -> usize {
177        let update = self.db_table().where_and("id", "=", id.into()).update(data);
178        update.as_usize().unwrap_or(0)
179    }
180    /// 监听
181    fn handle(&mut self) {}
182}