github.com/mdaxf/iac@v0.0.0-20240519030858-58a061660378/framework/cache/write_through.go (about) 1 // The package is migrated from beego, you can get from following link: 2 // import( 3 // "github.com/beego/beego/v2/client/cache" 4 // ) 5 // Copyright 2023. All Rights Reserved. 6 // 7 // Licensed under the Apache License, Version 2.0 (the "License"); 8 // you may not use this file except in compliance with the License. 9 // You may obtain a copy of the License at 10 // 11 // http://www.apache.org/licenses/LICENSE-2.0 12 // 13 // Unless required by applicable law or agreed to in writing, software 14 // distributed under the License is distributed on an "AS IS" BASIS, 15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 // See the License for the specific language governing permissions and 17 // limitations under the License. 18 19 package cache 20 21 import ( 22 "context" 23 "fmt" 24 "time" 25 26 "github.com/mdaxf/iac/framework/berror" 27 ) 28 29 type WriteThroughCache struct { 30 Cache 31 storeFunc func(ctx context.Context, key string, val any) error 32 } 33 34 // NewWriteThroughCache creates a write through cache pattern decorator. 35 // The fn is the function that persistent the key and val. 36 func NewWriteThroughCache(cache Cache, fn func(ctx context.Context, key string, val any) error) (*WriteThroughCache, error) { 37 if fn == nil || cache == nil { 38 return nil, berror.Error(InvalidInitParameters, "cache or storeFunc can not be nil") 39 } 40 41 w := &WriteThroughCache{ 42 Cache: cache, 43 storeFunc: fn, 44 } 45 return w, nil 46 } 47 48 func (w *WriteThroughCache) Set(ctx context.Context, key string, val any, expiration time.Duration) error { 49 err := w.storeFunc(ctx, key, val) 50 if err != nil { 51 return berror.Wrap(err, PersistCacheFailed, fmt.Sprintf("key: %s, val: %v", key, val)) 52 } 53 return w.Cache.Put(ctx, key, val, expiration) 54 }