requests2 0.1.62

simple http client by rust
Documentation
use std::{collections::HashMap, cell::RefCell, sync::{Mutex, Arc}};

use crate::value::Value;

/// # Cache 实现了trait store 它可以将数据存储到内部变量caches中
/// 新建db并写入存放到requests中,
/// '''
/// let db = Cache::new()
/// let mut rq = Requests::new(&data).connect("https://www.qq.com", Headers::Default)
/// '''
pub trait Store {
    type Item;

    fn pipes(&self, key: &str, result: Value);
    fn print(&self) ;
    fn print_json(&self);
    fn count(&self, key: &str) -> usize;
    fn get(&self, key:&str) -> Value;
}


pub trait Item {
    type Output;

    fn build(x: Self::Output) -> Box<Self::Output> where Self: Sized { Box::new(x) }
    
    // fn clone(&self) -> Self::Output;
}

#[derive(Clone, Debug)]
pub struct Person {
    pub name: String,
    pub age: u32,
}

impl Item for Person {
    type Output = Person;

    // fn clone(&self) -> Self::Output {
    //     Person {
    //         name: self.name.clone(),
    //         age: self.age,
    //     }
    // }
}



pub struct Cache {
    caches: Arc<Mutex<RefCell::<HashMap<String,Value>>>>,
}

impl Cache {

    pub fn new() -> Self {
        Cache {
            caches: Arc::new(Mutex::new(RefCell::new(HashMap::new()))),
        }
    }
}



impl Store for Cache  {
    type Item = Value;


    fn pipes(&self, key: &str, result: Self::Item) {
        let caches = Arc::clone(&self.caches);
        let caches = caches.lock().unwrap();
        (*caches).borrow_mut().insert(key.to_string(), result);
    }

    fn print_json(&self) {
        for (k, v) in self.caches.lock().unwrap().borrow().iter() {
            let data = serde_json::to_string(v).expect("not Serialize to string");
            println!("Key -- {:?} Value -- {:?}", k, data);
        }
    }

    fn print(&self) {
        for (k, v) in self.caches.lock().unwrap().borrow().iter() {
            println!("Key -- {:?} Value -- {:?}", k, v);
        }
    }

    fn count(&self, key:&str)  -> usize {
        let mut counter = 0;
        for (k, v) in self.caches.lock().unwrap().borrow().iter() {
            if k == key {
                match v {
                    Value::LIST(c) => counter = c.len(),
                    _ => counter = 1
                };
            }
        }
        counter
    }

    fn get(&self, key:&str) -> Value {
        for (k, v) in self.caches.lock().unwrap().borrow().iter() {
            if k == key {
                let data = serde_json::to_string(v).expect("not Serialize to string");
                let result = serde_json::from_str::<Value>(data.as_str()).expect("not Deserialize to string");
                return result;
            }
        }
        Value::NULL
    }

}