github.com/angenalZZZ/gofunc@v0.0.0-20210507121333-48ff1be3917b/data/cache/codec/codec.go (about) 1 package codec 2 3 import ( 4 "github.com/angenalZZZ/gofunc/data/cache/store" 5 "time" 6 ) 7 8 // Stats allows to returns some statistics of codec usage 9 type Stats struct { 10 Hits int 11 Miss int 12 SetSuccess int 13 SetError int 14 DeleteSuccess int 15 DeleteError int 16 InvalidateSuccess int 17 InvalidateError int 18 ClearSuccess int 19 ClearError int 20 } 21 22 // Codec represents an instance of a cache store 23 type Codec struct { 24 store store.Interface 25 stats *Stats 26 } 27 28 // New return a new codec instance 29 func New(store store.Interface) *Codec { 30 return &Codec{ 31 store: store, 32 stats: &Stats{}, 33 } 34 } 35 36 // Get allows to retrieve the value from a given key identifier 37 func (c *Codec) Get(key string) (interface{}, error) { 38 val, err := c.store.Get(key) 39 40 if err == nil { 41 c.stats.Hits++ 42 } else { 43 c.stats.Miss++ 44 } 45 46 return val, err 47 } 48 49 // Set allows to set a value for a given key identifier and also allows to specify an expiration time 50 func (c *Codec) Set(key string, value interface{}, options *store.Options) error { 51 err := c.store.Set(key, value, options) 52 53 if err == nil { 54 c.stats.SetSuccess++ 55 } else { 56 c.stats.SetError++ 57 } 58 59 return err 60 } 61 62 // TTL returns an expiration time 63 func (c *Codec) TTL(key string) (time.Duration, error) { 64 return c.store.TTL(key) 65 } 66 67 // Delete allows to remove a value for a given key identifier 68 func (c *Codec) Delete(key string) error { 69 err := c.store.Delete(key) 70 71 if err == nil { 72 c.stats.DeleteSuccess++ 73 } else { 74 c.stats.DeleteError++ 75 } 76 77 return err 78 } 79 80 // Invalidate invalidates some cach items from given options 81 func (c *Codec) Invalidate(options store.InvalidateOptions) error { 82 err := c.store.Invalidate(options) 83 84 if err == nil { 85 c.stats.InvalidateSuccess++ 86 } else { 87 c.stats.InvalidateError++ 88 } 89 90 return err 91 } 92 93 // Clear resets all codec store data 94 func (c *Codec) Clear() error { 95 err := c.store.Clear() 96 97 if err == nil { 98 c.stats.ClearSuccess++ 99 } else { 100 c.stats.ClearError++ 101 } 102 103 return err 104 } 105 106 // GetStore returns the store associated to this codec 107 func (c *Codec) GetStore() store.Interface { 108 return c.store 109 } 110 111 // GetStats returns some statistics about the current codec 112 func (c *Codec) GetStats() *Stats { 113 return c.stats 114 }