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
extern crate redis;
extern crate dns_lookup;

mod error;
mod memory_cache;
mod redis_cache;

use std::{any::Any, collections::HashMap};

pub use memory_cache::MemoryCache;
pub use redis_cache::RedisCache;
pub use error::CacheError;

pub type Result<T> = std::result::Result<T, CacheError>;

pub trait Cacheable {
    fn model_name() -> &'static str where Self: Sized;
    fn to_redis_obj(&self) -> Vec<(String, String)>;
    fn from_redis_obj(obj: HashMap<String, String>) -> Result<Self> where Self: Sized;
    fn as_any(&self) -> &Any;
}

pub trait CacheAccess {
    fn insert<K: ToString, O: Cacheable + Clone + 'static>(&mut self, key: K, obj: O) -> Result<()>;
    fn get<K: ToString, O: Cacheable + Clone + 'static>(&mut self, key: K) -> Option<O>;
    fn remove<K: ToString, O: Cacheable>(&mut self, key: K) -> Result<()>;
}

pub enum Cache {
    Memory(MemoryCache),
    Redis(RedisCache),
}

use Cache::*;

impl Cache {
    pub fn insert<K: ToString, O: Cacheable + Clone + 'static>(&mut self, key: K, obj: O) -> Result<()> {
        match *self {
            Memory(ref mut c) => c.insert(key, obj),
            Redis(ref mut c) => c.insert(key, obj),
        }
    }

    pub fn get<K: ToString, O: Cacheable + Clone + 'static>(&mut self, key: K) -> Option<O> {
        match *self {
            Memory(ref mut c) => c.get::<K, O>(key),
            Redis(ref mut c) => c.get::<K, O>(key),
        }
    }

    pub fn remove<K: ToString, O: Cacheable>(&mut self, key: K) -> Result<()> {
        match *self {
            Memory(ref mut c) => c.remove::<K, O>(key),
            Redis(ref mut c) => c.remove::<K, O>(key),
        }
    }
}