use json::{JsonValue, object}; use crate::Field; /// 字典字段 /// /// * field 字段名 /// * mode 模式 string /// * title 字段描述 /// * length 字段总长度(含小数位) /// * default 默认值 /// * empty 是否可空 /// * dec 小数位 pub struct Dict { pub require: bool, pub field: String, pub mode: String, pub title: String, pub table: String, pub fields: String, pub api: String, pub def: String, pub show: bool, pub describe: String, pub multiple: bool, pub multiple_count: i32, pub example: JsonValue, } impl Dict { pub fn new(require: bool, field: &str, title: &str, table: &str, fields: &str, api: &str) -> Self { Self { require, field: field.to_string(), mode: "dict".to_string(), title: title.to_string(), table: table.to_string(), api: api.to_string(), show: true, fields: fields.to_string(), describe: "".to_string(), def: "".to_string(), multiple: false, multiple_count: 1, example: JsonValue::Null, } } /// 多选数量 pub fn multiple(&mut self, count: i32) -> &mut Dict { self.multiple = count > 1; self.multiple_count = count; self } } impl Field for Dict { fn sql(&mut self, model: &str) -> String { match model { "sqlite" => { format!("{} text default ''", self.field) } _ => { let sql = format!("{} varchar({}) default ''", self.field, { if self.multiple { 64 * self.multiple_count + self.multiple_count } else { 64 } }); format!("{} comment '{}|{}|{}|{}|{}'", sql.clone(), self.mode, self.title, self.require, self.multiple, self.multiple_count) } } } fn hide(&mut self) -> &mut Self { self.show = false; self } fn describe(&mut self, text: &str) -> &mut Self { self.describe = text.to_string(); self } fn field(&mut self) -> JsonValue { let mut field = object! {}; field.insert("require", JsonValue::from(self.require)).unwrap(); field.insert("field", JsonValue::from(self.field.clone())).unwrap(); field.insert("mode", JsonValue::from(self.mode.clone())).unwrap(); field.insert("title", JsonValue::from(self.title.clone())).unwrap(); field.insert("table", JsonValue::from(self.table.clone())).unwrap(); field.insert("api", JsonValue::from(self.api.clone())).unwrap(); field.insert("fields", JsonValue::from(self.fields.clone())).unwrap(); field.insert("def", JsonValue::from(self.def.clone())).unwrap(); field.insert("multiple", JsonValue::from(self.multiple)).unwrap(); field.insert("multiple_count", JsonValue::from(self.multiple_count)).unwrap(); field.insert("show", JsonValue::from(self.show)).unwrap(); field.insert("describe", JsonValue::from(self.describe.clone())).unwrap(); field.insert("example", self.example.clone()).unwrap(); field } fn swagger(&mut self) -> JsonValue { object! { "type": self.mode.clone(), "example": self.example.clone(), } } fn example(mut self, data: JsonValue) -> Self { self.example = data.clone(); self } }