br_addon/
swagger.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
use std::collections::HashMap;
use json::{object, JsonValue};
use crate::action::Action;

#[derive(Clone)]
pub struct Swagger {
    openapi: String,
    info: Info,
    servers: Vec<Server>,
    /// 组件 密钥认证设置
    components: JsonValue,
    /// 分类标签
    tags: HashMap<String, Tag>,

    security: Vec<JsonValue>,
    /// 路径
    paths: HashMap<String, HashMap<String, Api>>,
}


impl Swagger {
    pub fn new(version: &str, title: &str, description: &str) -> Swagger {
        Swagger {
            openapi: "3.0.0".to_string(),
            info: Info {
                title: title.to_string(),
                description: description.to_string(),
                version: version.to_string(),
            },
            servers: vec![],
            components: object! {},
            tags: Default::default(),
            security: vec![],
            paths: Default::default(),
        }
    }
    pub fn add_server(&mut self, url: &str, description: &str) {
        self.servers.push(Server { url: url.to_string(), description: description.to_string() })
    }
    pub fn add_components_bearer_token(&mut self) {
        self.components["securitySchemes"]["BearerToken"] = object! {
            "type": "http",
            "scheme": "bearer",
            "bearerFormat": "Token"
        };
        self.security.push(object! {
            "BearerToken":[]
        })
    }
    pub fn add_authorization_header(&mut self, token: &str) {
        self.components["parameters"]["AuthorizationHeader"] = object! {
            "name": "Authorization",
            "in": "header",
            "required": true,
            "description": "Bearer token for authentication",
            "schema":{
                "type": "string",
                "example":format!("Bearer {}",token)
            }
        };
    }
    pub fn add_tags(&mut self, name: &str, description: &str) {
        self.tags.insert(name.to_string(), Tag { name: name.to_string(), description: description.to_string() });
    }
    pub fn add_paths(&mut self, mut action: Box<dyn Action>) {
        let path = format!("/{}/{}", action.version(), action.api().replace(".", "/"));
        let mut t = HashMap::new();
        t.insert(action.method().str().to_lowercase().clone(), Api::new(action));
        self.paths.insert(path, t);
    }
    pub fn json(&mut self) -> JsonValue {
        let mut paths = HashMap::new();
        for (key, value) in self.paths.iter_mut() {
            let mut t = HashMap::new();
            for (x, y) in value.iter_mut() {
                t.insert(x.clone(), y.json().clone());
            }
            paths.insert(key.clone(), t.clone());
        }
        object! {
            openapi: self.openapi.clone(),
            info: self.info.json(),
            servers: self.servers.iter().map(|x|x.json()).collect::<Vec<JsonValue>>().clone(),
            components: self.components.clone(),
            security:self.security.clone(),
            tags: self.tags.values().map(|y| y.json()).collect::<Vec<JsonValue>>().clone(),
            paths: paths.clone()
        }
    }
}
/// 接口项目信息
#[derive(Clone)]
struct Info {
    /// 项目标题
    title: String,
    /// 项目描述
    description: String,
    /// 项目版本
    version: String,
}
impl Info {
    pub fn json(&self) -> JsonValue {
        object! {
            title: self.title.clone(),
            description: self.description.clone(),
            version: self.version.clone()
        }
    }
}
/// 服务器地址
#[derive(Clone)]
struct Server {
    url: String,
    description: String,
}
impl Server {
    pub fn json(&self) -> JsonValue {
        object! {
            url: self.url.clone(),
            description: self.description.clone(),
        }
    }
}
/// 标签分类
#[derive(Clone)]
struct Tag {
    /// 标签名称
    name: String,
    /// 标签描述
    description: String,
}
impl Tag {
    pub fn json(&self) -> JsonValue {
        object! {
            name: self.name.clone(),
            description: self.description.clone(),
        }
    }
}
#[derive(Clone)]
struct Api {
    tags: Vec<String>,
    summary: String,
    description: String,
    /// 请求消息体
    request_body: RequestBody,
    /// 响应消息体
    responses: JsonValue,
}

impl Api {
    pub fn new(mut action: Box<dyn Action>) -> Api {
        let mut t = Self {
            tags: vec![action.api().split(".").next().unwrap().to_string()],
            summary: action.title(),
            description: action.description(),
            request_body: RequestBody::new(),
            responses: object! {},
        };
        if !action.params().is_empty() {
            t.request_body.set_required(true);
            t.request_body.set_content(action.content_type().str().as_str(), action.params());
        }
        t
    }
    pub fn json(&self) -> JsonValue {
        let mut t = object! {
            tags:self.tags.clone(),
            summary: self.summary.clone(),
            description: self.description.clone(),
            requestBody: self.request_body.json(),
            responses: self.responses.clone(),
        };
        if !t["requestBody"]["required"].as_bool().unwrap() {
            t.remove("requestBody");
        }
        t
    }
}

#[derive(Clone)]
struct RequestBody {
    required: bool,
    content: JsonValue,
}
impl RequestBody {
    pub fn new() -> RequestBody {
        Self { required: false, content: object! {} }
    }
    pub fn set_required(&mut self, state: bool) {
        self.required = state;
    }
    pub fn set_content(&mut self, content_type: &str, params: JsonValue) {
        self.content[content_type] = object! {
            schema:object! {"type":if params.is_array() {"array"}else{"object"}}
        };
        match self.content[content_type]["schema"]["type"].as_str().unwrap_or("") {
            "object" => RequestBody::set_schema_object(&mut self.content[content_type]["schema"], params.clone()),
            "array" => RequestBody::set_schema_array(&mut self.content[content_type]["schema"], params.clone()),
            _ => {}
        }
        for (field, data) in params.entries() {
            self.content[content_type]["example"][field] = data["example"].clone();
        }
    }
    fn set_schema_object(data: &mut JsonValue, params: JsonValue) {
        for (key, value) in params.entries() {
            data["properties"][key]["type"] = RequestBody::mode(value["mode"].as_str().unwrap_or(""));
            match data["properties"][key]["type"].as_str().unwrap_or("") {
                "object" => RequestBody::set_sub_object(&mut data["properties"][key], value["items"].clone()),
                "array" => RequestBody::set_sub_array(&mut data["properties"][key], value["items"].clone()),
                _ => RequestBody::set_schema_str(&mut data["properties"][key], value.clone()),
            }
        }
    }
    fn set_schema_str(data: &mut JsonValue, params: JsonValue) {
        data["type"] = RequestBody::mode(params["mode"].as_str().unwrap_or(""));
        data["example"] = params["example"].clone();
    }
    fn set_schema_array(data: &mut JsonValue, params: JsonValue) {
        data["items"] = params;
    }
    fn set_sub_array(data: &mut JsonValue, params: JsonValue) {
        data["items"]["type"] = params["mode"].as_str().unwrap_or("string").into();
    }
    fn set_sub_object(data: &mut JsonValue, params: JsonValue) {
        for (key, value) in params.entries() {
            data["properties"][key]["type"] = RequestBody::mode(value["mode"].as_str().unwrap_or(""));
            match data["properties"][key]["type"].as_str().unwrap_or("") {
                "object" => RequestBody::set_sub_object(&mut data["properties"][key], value["items"].clone()),
                "array" => RequestBody::set_sub_array(&mut data["properties"][key], value["items"].clone()),
                _ => RequestBody::set_schema_str(&mut data["properties"][key], value.clone()),
            }
        }
    }
    fn mode(name: &str) -> JsonValue {
        match name {
            "array" => "array",
            "int" => "integer",
            "switch" => "boolean",
            "radio" => "string",
            _ => name
        }.into()
    }
    pub fn json(&self) -> JsonValue {
        object! {
                required: self.required,
                content: self.content.clone()
        }
    }
}