use serde_json::{Map, Value};
use crate::method::method_structure::MethodResult;
pub struct JsonResponseFormatter {
response: Vec<Value>,
}
pub trait ResponseFormatter {
fn clear(&mut self);
fn get_value(&self) -> Value;
fn add_error(&mut self, message: &String);
fn add_info(&mut self, message: &String);
fn add_debug(&mut self, message: &String);
fn add_success(&mut self, message: &String);
fn add_markdown(&mut self, message: &String);
fn add_list(&mut self, items: Vec<Value>);
fn add_table(&mut self, items: Map<String, Value>);
}
impl JsonResponseFormatter {
pub fn new() -> Self {
Self {
response: vec![]
}
}
pub fn error(message: &String) -> MethodResult {
let mut formatter = Self::new();
formatter.add_error(message);
formatter.as_result(1)
}
pub fn table(items: Map<String, Value>) -> MethodResult {
let mut formatter = Self::new();
formatter.add_table(items);
formatter.as_result(1)
}
pub fn as_result(&self, code: i8) -> MethodResult {
MethodResult {
code,
message: Some(self.get_value()),
}
}
fn get_named_value(&self, name: &str, value: &Value) -> Value {
let mut map = Map::new();
map.insert(String::from(name.clone()), value.clone());
Value::from(map)
}
}
impl ResponseFormatter for JsonResponseFormatter {
fn clear(&mut self) {
self.response.clear();
}
fn get_value(&self) -> Value {
Value::from(self.response.clone())
}
fn add_error(&mut self, message: &String) {
self.response.push(self.get_named_value("error", &Value::from(message.clone())));
}
fn add_info(&mut self, message: &String) {
self.response.push(self.get_named_value("info", &Value::from(message.clone())));
}
fn add_debug(&mut self, message: &String) {
self.response.push(self.get_named_value("debug", &Value::from(message.clone())));
}
fn add_success(&mut self, message: &String) {
self.response.push(self.get_named_value("success", &Value::from(message.clone())));
}
fn add_markdown(&mut self, message: &String) {
self.response.push(self.get_named_value("markdown", &Value::from(message.clone())));
}
fn add_list(&mut self, items: Vec<Value>) {
self.response.push(self.get_named_value(
"list",
&Value::from(items),
))
}
fn add_table(&mut self, items: Map<String, Value>) {
self.response.push(self.get_named_value(
"table",
&Value::from(items),
))
}
}